"""Custom startup banner for Sitemule Blueprint MCP Server.

Replaces the default FastMCP banner with Sitemule branding.
Uses the same Rich-based rendering approach.
"""

import subprocess
from importlib.metadata import version as pkg_version
from pathlib import Path

from rich.align import Align
from rich.console import Console, Group
from rich.panel import Panel
from rich.table import Table
from rich.text import Text


def _read_build_info() -> tuple[str, str]:
    """Return (git_hash, build_date), reading from _build_info.py if present,
    otherwise falling back to a live `git` call (dev mode)."""
    try:
        from blueprint_mcp._build_info import GIT_HASH, BUILD_DATE  # type: ignore
        return GIT_HASH, BUILD_DATE
    except ImportError:
        pass
    # Dev fallback: ask git directly
    try:
        root = Path(__file__).resolve().parent.parent.parent.parent
        git_hash = subprocess.check_output(
            ["git", "rev-parse", "--short", "HEAD"], cwd=root, stderr=subprocess.DEVNULL
        ).decode().strip()
    except Exception:
        git_hash = "dev"
    from datetime import datetime, timezone
    build_date = datetime.now(timezone.utc).strftime("%Y-%m-%d")
    return git_hash, build_date

# ── Block-art for "BLUEPRINT" ─────────────────────────────────────────────
# Uses the box-drawing style from banner.txt

_ART_LINES = [
    "██████╗ ██╗     ██╗   ██╗███████╗██████╗ ██████╗ ██╗███╗   ██╗████████╗",
    "██╔══██╗██║     ██║   ██║██╔════╝██╔══██╗██╔══██╗██║████╗  ██║╚══██╔══╝",
    "██████╔╝██║     ██║   ██║█████╗  ██████╔╝██████╔╝██║██╔██╗ ██║   ██║   ",
    "██╔══██╗██║     ██║   ██║██╔══╝  ██╔═══╝ ██╔══██╗██║██║╚██╗██║   ██║   ",
    "██████╔╝███████╗╚██████╔╝███████╗██║     ██║  ██║██║██║ ╚████║   ██║   ",
    "╚═════╝ ╚══════╝ ╚═════╝ ╚══════╝╚═╝     ╚═╝  ╚═╝╚═╝╚═╝  ╚═══╝   ╚═╝   ",
]


def _blue_gradient(text: str) -> str:
    """Apply a cyan→blue ANSI true-color gradient to visible characters."""
    visible_count = sum(1 for ch in text if ch not in (" ", "\n"))
    if visible_count == 0:
        return text

    parts: list[str] = []
    vi = 0
    for ch in text:
        if ch in (" ", "\n"):
            parts.append(ch)
        else:
            # Green channel sweeps 198 → 100 (bright cyan-blue → deeper blue)
            t = vi / max(visible_count - 1, 1)
            g = int(198 - 98 * t)
            parts.append(f"\x1b[38;2;0;{g};255m{ch}")
            vi += 1
    parts.append("\x1b[39m")
    return "".join(parts)


_LOGO = "\n".join(_blue_gradient(line) for line in _ART_LINES)


def log_banner() -> None:
    """Print the Sitemule Blueprint MCP startup banner to stderr."""
    try:
        ver = pkg_version("blueprint-mcp")
    except Exception:
        ver = "dev"

    git_hash, build_date = _read_build_info()

    logo_text = Text.from_ansi(_LOGO, no_wrap=True)
    title_text = Text("Sitemule Blueprint MCP", style="bold blue")

    info_table = Table.grid(padding=(0, 1))
    info_table.add_column(style="bold", justify="center")
    info_table.add_column(style="cyan", justify="left")
    info_table.add_column(style="dim", justify="left")

    info_table.add_row("\U0001f5a5", " Server:", f"Blueprint MCP {ver}")
    info_table.add_row("\U0001f4e6", " Build:",  f"{git_hash}  ({build_date})")
    info_table.add_row("\U0001f310", " Visit:",  "https://sitemule.com/blueprint")

    panel_content = Group(
        "",
        Align.center(logo_text),
        "",
        Align.center(title_text),
        "",
        Align.center(info_table),
    )

    panel = Panel(
        panel_content,
        border_style="dim",
        padding=(1, 4),
    )

    console = Console(stderr=True)
    console.print(Group("\n", Align.center(panel), "\n"))
