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

import sys
import json

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, MEMORY_FILE, load_access
import requests

# 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",            "Launch the interactive agent REPL", "onefirewall-ai")
    table.add_row("onefirewall-ai login",       "Configure endpoint & API key",      "onefirewall-ai login")
    table.add_row("onefirewall-ai version",     "Show version info",                 "onefirewall-ai version")
    table.add_row("", "", "")

    # Chat
    table.add_row('onefirewall-ai "message"',   "Send message & stream response",    'onefirewall-ai "hello"')
    table.add_row('onefirewall-ai chat',        "Launch chat-only REPL",             "onefirewall-ai chat")
    table.add_row("cat file | onefirewall-ai",  "Send piped input to the AI",        "cat logs.txt | onefirewall-ai fix this")
    table.add_row("", "", "")

    # Sessions
    table.add_row("onefirewall-ai sessions",              "List all sessions",             "onefirewall-ai sessions")
    table.add_row("onefirewall-ai sessions view <id>",    "View full session history",     "onefirewall-ai sessions view agent_abc")
    table.add_row("onefirewall-ai --session <id> ...",    "Resume a specific session",     'onefirewall-ai --session myapp "continue"')
    table.add_row("", "", "")

    # Agent
    table.add_row('onefirewall-ai agent "task"',             "[Agent] New autonomous session",     'onefirewall-ai agent "build a todo app"')
    table.add_row('onefirewall-ai agent',                    "[Agent] Launch agent REPL",           "onefirewall-ai agent")
    table.add_row('onefirewall-ai --session <name> agent',   "[Agent] Named/resumable session",    'onefirewall-ai --session myapp agent "add tests"')

    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]")


def sync_memory(quiet: bool = False) -> bool:
    """Fetch latest user memory from the server and update local MEMORY.md."""
    if not is_logged_in():
        return False

    acc = load_access()
    endpoint = acc.get("endpoint")
    api_key = acc.get("api_key")

    if not endpoint or not api_key:
        return False

    url = endpoint.rstrip("/") + "/api/user/memory"
    headers = {"Authorization": f"Bearer {api_key}"}

    try:
        if not quiet:
            console.print("[dim]Syncing profile memory...[/dim]")
        
        r = requests.get(url, headers=headers, timeout=10)
        if r.status_code == 200:
            try:
                data = r.json()
                memory_md = data.get("memory") or ""
            except (ValueError, json.JSONDecodeError):
                if not quiet:
                    console.print("[yellow]! Could not decode memory from server.[/yellow]")
                return False

            if memory_md:
                MEMORY_FILE.parent.mkdir(parents=True, exist_ok=True)
                MEMORY_FILE.write_text(memory_md, encoding="utf-8")
                if not quiet:
                    console.print("[bold green]✓ Synced profile memory[/bold green]")
                return True
            else:
                if not quiet:
                    console.print("[dim]No profile memory found on server.[/dim]")
                    console.print("[dim]Tip: Go to the dashboard to personalize your AI profile.[/dim]")
                return True # Technically a successful sync of "nothing"
        else:
            if not quiet:
                console.print(f"[yellow]! Server returned {r.status_code} for memory sync.[/yellow]")
    except Exception as e:
        if not quiet:
            console.print(f"[dim]Note: Could not sync profile memory: {e}[/dim]")
    
    return False
