"""Welcome banner widget for ieum."""

from __future__ import annotations

import shutil
import sys
from typing import Any

from rich.style import Style
from rich.text import Text
from textual.widgets import Static

from ieum.config import IEUM_ASCII, settings
from ieum.i18n import t


def _check_ripgrep() -> bool:
    """Check if ripgrep is installed."""
    return shutil.which("rg") is not None


def _get_ripgrep_install_hint() -> str:
    """Get platform-specific ripgrep install command."""
    if sys.platform == "win32":
        return "winget install BurntSushi.ripgrep.MSVC"
    elif sys.platform == "darwin":
        return "brew install ripgrep"
    else:
        return "apt install ripgrep"


class WelcomeBanner(Static):
    """Welcome banner displayed at startup."""

    DEFAULT_CSS = """
    WelcomeBanner {
        height: auto;
        padding: 1;
        margin-bottom: 1;
    }
    """

    def __init__(self, **kwargs: Any) -> None:
        """Initialize the welcome banner."""
        super().__init__(self._build_banner(), **kwargs)

    def _build_banner(self) -> Text:
        """Build the banner rich text."""
        banner = Text()
        banner.append(IEUM_ASCII + "\n", style=Style(bold=True, color="#10b981"))

        # Show LangFuse tracing status
        if settings.has_langfuse:
            host = settings.langfuse_host or "https://cloud.langfuse.com"
            # Extract display name from host
            if "localhost" in host or "127.0.0.1" in host:
                display_host = "localhost"
            elif "cloud.langfuse.com" in host:
                display_host = "cloud"
            else:
                # Extract domain from URL
                display_host = host.replace("https://", "").replace("http://", "").split("/")[0]

            banner.append("✓ ", style="green")
            banner.append("LangFuse tracing: ")
            banner.append(display_host, style=Style(color="cyan", link=host))
            banner.append("\n")

        banner.append(t("welcome.title") + "\n", style="#10b981")
        banner.append(t("welcome.hints") + "\n", style="dim")

        # Check for ripgrep and show warning if not installed
        if not _check_ripgrep():
            banner.append("\n")
            banner.append("⚠ ", style="yellow")
            banner.append(t("welcome.ripgrep_missing"), style="yellow")
            banner.append(f"{_get_ripgrep_install_hint()}", style="dim italic")

        return banner
