"""Service for loading hook configurations."""

from __future__ import annotations

from typing import TYPE_CHECKING

from portal.core.domain.models import Hook, HookStage

if TYPE_CHECKING:
    from pathlib import Path

    from portal.core.domain.models import PortalConfig
    from portal.core.services.config_service import ConfigService


class HookConfigService:
    """Service for loading hook configurations."""

    def __init__(self, config_service: ConfigService):
        self.config_service = config_service

    async def get_hooks_for_stage(
        self, stage: HookStage, project_path: Path | None = None, template_name: str | None = None
    ) -> list[Hook]:
        """Get hooks configured for a specific stage, including project-level overrides.

        Args:
            stage: Hook stage to get hooks for
            project_path: Path to project for loading project-specific config
            template_name: Optional template name to include template hooks

        Returns:
            List of hooks for the stage, with project overrides applied
        """
        # Load configuration with project-level overrides
        config = await self.config_service.get_config(project_path)
        return self._extract_hooks_from_config(config, stage, template_name)

    def get_hooks_for_stage_sync(
        self, config: PortalConfig, stage: HookStage, template_name: str | None = None
    ) -> list[Hook]:
        """Get hooks configured for a specific stage (synchronous version for backward compatibility).

        Args:
            config: Portal configuration
            stage: Hook stage to get hooks for
            template_name: Optional template name to include template hooks

        Returns:
            List of hooks for the stage
        """
        return self._extract_hooks_from_config(config, stage, template_name)

    def _extract_hooks_from_config(
        self, config: PortalConfig, stage: HookStage, template_name: str | None = None
    ) -> list[Hook]:
        """Extract hooks from configuration for a specific stage.

        Args:
            config: Portal configuration
            stage: Hook stage to get hooks for
            template_name: Optional template name to include template hooks

        Returns:
            List of hooks for the stage
        """
        hooks = []

        # Get hooks from main config
        if hasattr(config, "hooks") and stage.value in config.hooks:
            stage_hooks = config.hooks[stage.value]
            if isinstance(stage_hooks, list):
                for hook_dict in stage_hooks:
                    try:
                        hook = Hook.model_validate(hook_dict)
                        hooks.append(hook)
                    except Exception:
                        # Skip invalid hooks
                        pass

        # Add template hooks if using a template
        if template_name and hasattr(config, "templates"):
            templates = config.templates
            if isinstance(templates, dict) and template_name in templates:
                template = templates[template_name]
                if isinstance(template, dict) and "hooks" in template:
                    template_hooks = template["hooks"]
                    if isinstance(template_hooks, dict) and stage.value in template_hooks:
                        for hook_dict in template_hooks[stage.value]:
                            try:
                                hook = Hook.model_validate(hook_dict)
                                hooks.append(hook)
                            except Exception:
                                # Skip invalid hooks
                                pass

        return hooks
