"""macOS Terminal.app adapter for Portal external integrations."""

from __future__ import annotations

import os
from typing import TYPE_CHECKING, Any

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


class TerminalAdapter:
    """Adapter for macOS Terminal.app."""

    def is_available(self) -> bool:
        """Check if running in Terminal.app."""
        return os.environ.get("TERM_PROGRAM") == "Apple_Terminal"

    async def set_title(self, title: str) -> bool:
        """Set terminal window title."""
        if not self.is_available():
            return False

        # Use escape sequence
        print(f"\033]0;{title}\007", end="", flush=True)
        return True

    async def apply_theme(self, color: WorktreeColor) -> bool:
        """Apply color theme to Terminal.app."""
        # Terminal.app has limited color customization
        # We can only set the window title
        return await self.set_title(f"Portal: {color.name}")

    def get_status(self) -> dict[str, Any]:
        """Get Terminal.app integration status."""
        return {
            "available": self.is_available(),
            "name": "Terminal.app",
            "version": self._get_terminal_version(),
            "features": {
                "window_title": self.is_available(),
                "tab_colors": False,  # Not supported
                "dynamic_profiles": False,  # Not supported
            },
        }

    def _get_terminal_version(self) -> str:
        """Get Terminal.app version if available."""
        if not self.is_available():
            return "Not available"

        # Terminal.app version is tied to macOS version
        try:
            import platform

            return f"macOS {platform.mac_ver()[0]}"
        except Exception:
            return "Unknown"
