"""Base editor adapter with shared functionality."""

from __future__ import annotations

import asyncio
import subprocess
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from portal.core.domain.models.color import WorktreeColor
    from portal.core.services.color_theme_service import ColorThemeService


class BaseEditorAdapter:
    """Base class for editor adapters with shared functionality."""

    def __init__(self, color_theme_service: ColorThemeService | None = None) -> None:
        """Initialize with color theme service for shared functionality."""
        from portal.core.services.color_theme_service import ColorThemeService

        self._color_theme_service = color_theme_service or ColorThemeService()

    async def _safe_subprocess_run(self, command: list[str], timeout: int = 5) -> tuple[bool, str]:
        """Safely run subprocess with security and timeout."""
        try:
            result = await asyncio.create_subprocess_exec(
                *command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
            )
            stdout, stderr = await asyncio.wait_for(result.communicate(), timeout=timeout)

            if result.returncode == 0:
                return True, stdout.decode().strip()
            else:
                return False, stderr.decode().strip()

        except (TimeoutError, subprocess.SubprocessError):
            return False, "Command timed out or failed"
        except Exception:
            return False, "Unknown error"

    def _get_activity_bar_color(self, color: WorktreeColor) -> str:
        """Get activity bar color using existing color theme service."""
        return self._color_theme_service._darken_hex(color.hex, 0.3)

    def _get_contrast_text_color(self, color: WorktreeColor) -> str:
        """Get appropriate text color for contrast."""
        return "#FFFFFF" if color.is_dark else "#000000"
