"""
utils.py — Terminal helpers: banner, help table, and misc utilities.
"""

import sys

from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich import box
from rich.text import Text

from onefirewall_ai import __version__
from onefirewall_ai.config import HOME_DIR, is_logged_in

# Force UTF-8 on Windows to avoid charmap encoding errors
console = Console(force_terminal=True, highlight=False)

_LOGO = r"""
   ___                ______ _                        _ _
  / _ \              |  ____(_)                      | | |
 | | | |_ __   ___  | |__   _ _ __ _____      ____ _| | |
 | | | | '_ \ / _ \ |  __| | | '__/ _ \ \ /\ / / _` | | |
 | |_| | | | |  __/ | |    | | | |  __/\ V  V / (_| | | |
  \___/|_| |_|\___| |_|    |_|_|  \___| \_/\_/ \__,_|_|_|
"""


def print_banner() -> None:
    """Print the OneFirewall AI Banner."""
    console.print(f"[bold cyan]{_LOGO}[/bold cyan]")
    console.print(
        f"  [dim]AI Gateway CLI[/dim]  [bold white]v{__version__}[/bold white]\n"
    )


def print_help() -> None:
    """Print styled help table."""
    print_banner()

    table = Table(
        box=box.ROUNDED,
        show_header=True,
        header_style="bold cyan",
        border_style="dim",
        expand=False,
        min_width=70,
    )
    table.add_column("Command", style="bold white", no_wrap=True)
    table.add_column("Description", style="white")
    table.add_column("Example", style="dim cyan")

    table.add_row(
        "onefirewall-ai",
        "Show this help message",
        "onefirewall-ai",
    )
    table.add_row(
        "onefirewall-ai help",
        "Show this help message",
        "onefirewall-ai help",
    )
    table.add_row(
        "onefirewall-ai login",
        "Configure endpoint & API key",
        "onefirewall-ai login",
    )
    table.add_row(
        "onefirewall-ai <message>",
        "Send a message and stream the AI response",
        'onefirewall-ai "what is kubernetes?"',
    )
    table.add_row(
        "onefirewall-ai version",
        "Show version info",
        "onefirewall-ai version",
    )

    console.print(table)
    console.print()

    # Status line — use ASCII-safe markers for Windows compat
    logged = is_logged_in()
    if logged:
        status_icon = "[bold green][ON][/bold green]"
        status_text = "[green]Logged in[/green]"
    else:
        status_icon = "[bold red][--][/bold red]"
        status_text = "[red]Not logged in[/red] — run [cyan]onefirewall-ai login[/cyan]"
    console.print(f"  Status  {status_icon} {status_text}")
    console.print(f"  Config  [dim]{HOME_DIR}[/dim]")
    console.print()


def print_version() -> None:
    """Print version info."""
    console.print(f"onefirewall-ai [bold cyan]v{__version__}[/bold cyan]")
