"""Adapter for HookService to match HookServiceProtocol."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from portal.core.domain.models import BaseResult, HookExecutionResult, HookStage, Worktree

if TYPE_CHECKING:
    from portal.core.domain.models import PortalConfig
    from portal.core.services.hook_config_service import HookConfigService
    from portal.core.services.hook_service import HookService


class HookServiceAdapter:
    """Adapter to make HookService compatible with HookServiceProtocol."""

    def __init__(
        self,
        hook_service: HookService,
        hook_config_service: HookConfigService,
        config: PortalConfig,
    ):
        self._hook_service = hook_service
        self._hook_config_service = hook_config_service
        self._config = config

    async def execute_hooks(self, stage: str, context: dict[str, Any]) -> BaseResult:
        """Execute hooks for a specific stage.

        Args:
            stage: Hook stage (e.g., 'pre_create', 'post_create')
            context: Context data for hooks including worktree info

        Returns:
            BaseResult with success status and any errors
        """
        # Convert stage string to HookStage enum
        try:
            hook_stage = HookStage(stage)
        except ValueError:
            return BaseResult(success=False, errors=[f"Invalid hook stage: {stage}"])

        # Extract worktree from context
        worktree_data = context.get("worktree", {})
        if not worktree_data:
            return BaseResult(success=False, errors=["No worktree data in context"])

        # Create Worktree instance from data
        try:
            if isinstance(worktree_data, dict):
                # Create minimal Worktree object with required fields
                from datetime import datetime
                from pathlib import Path

                worktree = Worktree(
                    id=worktree_data.get("id", ""),
                    path=Path(worktree_data.get("path", ".")),
                    branch=worktree_data.get("branch", ""),
                    name=worktree_data.get("name", ""),
                    head_sha=worktree_data.get("head_sha", "unknown"),
                    status=worktree_data.get("status", "active"),
                    created_at=worktree_data.get("created_at", datetime.now()),
                    last_accessed=worktree_data.get("last_accessed", datetime.now()),
                )
            else:
                # Assume it's already a Worktree object
                worktree = worktree_data
        except Exception as e:
            return BaseResult(success=False, errors=[f"Failed to parse worktree data: {e}"])

        # Get hooks for this stage with project-level overrides
        template_name = context.get("template")

        # Try to determine project path from worktree path or context
        project_path = None
        if hasattr(worktree, "path") and worktree.path:
            # Use the hook service's project root finding method
            project_path = self._hook_service._find_project_root(worktree.path)

        # Use async method to get hooks with project-level overrides
        hooks = await self._hook_config_service.get_hooks_for_stage(
            hook_stage, project_path, template_name
        )

        if not hooks:
            # No hooks configured for this stage
            return BaseResult(success=True)

        # Execute hooks
        hook_result = await self._hook_service.execute_hooks(hook_stage, hooks, worktree, context)

        # Create HookExecutionResult with hook details
        return HookExecutionResult(
            success=hook_result.success,
            errors=hook_result.errors,
            warnings=hook_result.warnings,
            hook_details={
                "executed": hook_result.executed,
                "skipped": hook_result.skipped,
                "failed": hook_result.failed,
                "duration_ms": hook_result.duration_ms,
            },
        )

    async def register_hook(self, stage: str, hook_name: str, command: str) -> BaseResult:  # noqa: ARG002
        """Register a new hook (not implemented in current design).

        Args:
            stage: Hook stage
            hook_name: Unique name for the hook
            command: Command to execute

        Returns:
            BaseResult with success status and any errors
        """
        # This method is not implemented in the current design
        # Hooks are configured via YAML configuration
        return BaseResult(
            success=False,
            errors=["Dynamic hook registration not supported. Please use YAML configuration."],
        )

    def has_warnings(self) -> bool:
        """Check if the last execution had warnings.

        This is a helper method to match the expected interface.
        """
        # This would need to track the last result if needed
        return False
