"""
FORGE Terminal UI — Rich-powered display engine.
Sophisticated live rendering: agent status board, live log, progress bar.
"""
from __future__ import annotations

import time
from datetime import datetime
from typing import Optional

from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn, TimeElapsedColumn
from rich.live import Live
from rich.layout import Layout
from rich.columns import Columns
from rich import box

from forge.core.session import LogEntry, AgentRun, AgentStatus, GenerationSession, AppPlan

console = Console()

AGENT_COLORS = {
    "PLANNER":   "bright_blue",
    "ARCHITECT": "magenta",
    "CODEGEN":   "green",
    "VALIDATOR": "cyan",
    "TESTER":    "bright_cyan",
    "PACKAGER":  "yellow",
    "FORGE":     "bright_yellow",
    "SYSTEM":    "dim white",
}

LEVEL_STYLES = {
    "success":   "[bold green]✓[/bold green]",
    "warning":   "[yellow]⚠[/yellow]",
    "error":     "[bold red]✗[/bold red]",
    "highlight": "[bold yellow]★[/bold yellow]",
    "info":      "[dim]›[/dim]",
}

_start_time: float = time.time()


def set_start() -> None:
    global _start_time
    _start_time = time.time()


def elapsed_str() -> str:
    delta = time.time() - _start_time
    return f"{delta:06.2f}s"


def print_banner() -> None:
    t = Text()
    t.append("\n")
    t.append("  ███████╗ ██████╗ ██████╗  ██████╗ ███████╗\n", "bold bright_yellow")
    t.append("  ██╔════╝██╔═══██╗██╔══██╗██╔════╝ ██╔════╝\n", "bold yellow")
    t.append("  █████╗  ██║   ██║██████╔╝██║  ███╗█████╗  \n", "bold yellow")
    t.append("  ██╔══╝  ██║   ██║██╔══██╗██║   ██║██╔══╝  \n", "bold yellow")
    t.append("  ██║     ╚██████╔╝██║  ██║╚██████╔╝███████╗\n", "bold bright_yellow")
    t.append("  ╚═╝      ╚═════╝ ╚═╝  ╚═╝ ╚═════╝ ╚══════╝\n", "bold bright_yellow")
    t.append("\n  AI Mobile App Generator ", "bold white")
    t.append("v2.0  ", "dim")
    t.append("Groq", "bold red")
    t.append(" + ", "dim")
    t.append("NVIDIA NIM", "bold green")
    t.append(" + ", "dim")
    t.append("Telegram", "bold blue")
    t.append("\n")
    console.print(t)


def print_divider(title: str = "") -> None:
    if title:
        console.print(f"\n  [bold dim]{'─'*20}[/bold dim] [bold white]{title}[/bold white] [bold dim]{'─'*20}[/bold dim]\n")
    else:
        console.print(f"  [bold dim]{'─'*60}[/bold dim]")


def log_line(entry: LogEntry) -> None:
    color = AGENT_COLORS.get(entry.agent, "white")
    prefix = LEVEL_STYLES.get(entry.level, "›")
    console.print(
        f"  [dim]{entry.elapsed:06.1f}s[/dim]  "
        f"[{color}]{entry.agent:<10}[/{color}]  "
        f"{prefix} {entry.message}"
    )


def print_agent_header(name: str, engine: str) -> None:
    color = AGENT_COLORS.get(name, "white")
    icons = {
        "PLANNER": "🧠", "ARCHITECT": "🏗", "CODEGEN": "⚙️",
        "VALIDATOR": "✅", "TESTER": "🧪", "PACKAGER": "📦",
    }
    icon = icons.get(name, "▶")
    console.print(f"\n  [{color}]{icon}  AGENT: {name}[/{color}]  [dim]{engine}[/dim]")


def render_plan_panel(plan: AppPlan) -> None:
    t = Table(box=box.SIMPLE, show_header=False, padding=(0, 2))
    t.add_column("Key", style="dim", width=18)
    t.add_column("Value", style="white")

    t.add_row("App", f"[bold]{plan.app_name}[/bold]")
    t.add_row("Tagline", f"[italic]{plan.tagline}[/italic]")
    t.add_row("Package", plan.package_name)
    t.add_row(
        "Screens",
        f"[bold]{len(plan.screens)}[/bold]: " + ", ".join(s["name"] for s in plan.screens),
    )
    t.add_row("Navigation", plan.navigation)
    t.add_row("Storage", plan.storage)
    t.add_row("Auth", plan.auth_method)
    t.add_row("Models", ", ".join(m["name"] for m in plan.data_models))
    t.add_row(
        "Colors",
        f"Primary [bold]{plan.primary_color}[/bold]  "
        f"Accent [bold]{plan.accent_color}[/bold]  "
        f"BG [bold]{plan.background_color}[/bold]",
    )
    if plan.features:
        t.add_row("Features", f"{len(plan.features)} defined")
    if plan.assumptions:
        t.add_row("Assumptions", f"{len(plan.assumptions)} noted")

    console.print(Panel(t, title="[bold yellow]📋 APP PLAN[/bold yellow]", border_style="yellow"))


def render_success(session: GenerationSession) -> None:
    plan = session.plan
    elapsed = session.elapsed

    content = Text()
    content.append(f"\n  ✅  {plan.app_name}\n", "bold green")
    content.append(f"  {plan.tagline}\n\n", "italic dim")

    content.append(f"  📁 Project:    ", "dim")
    content.append(f"{session.project_dir}\n", "bold white")
    content.append(f"  📦 Zip:        ", "dim")
    content.append(f"{session.zip_path}\n\n", "bold white")

    # Stats grid
    stats = [
        ("Files", str(session.total_files)),
        ("Lines", f"{session.total_lines:,}"),
        ("Screens", str(len(plan.screens))),
        ("Time", f"{elapsed:.1f}s"),
        ("NVIDIA files", str(session.nvidia_files)),
        ("Groq files", str(session.groq_files)),
    ]
    for label, value in stats:
        content.append(f"  {label:<16}", "dim")
        content.append(f"{value}\n", "bold yellow")

    console.print(Panel(content, border_style="green", title="[bold green]🎉 GENERATION COMPLETE[/bold green]"))

    console.print("\n  [bold]Next steps:[/bold]")
    slug = plan.slug
    console.print(f"    [dim]$[/dim]  [cyan]cd {slug}[/cyan]")
    console.print(f"    [dim]$[/dim]  [cyan]npm install[/cyan]")
    console.print(f"    [dim]$[/dim]  [cyan]npx expo start[/cyan]")
    console.print(f"\n  Scan the QR with [bold]Expo Go[/bold] on your device.\n")


def print_doctor_result(results: dict) -> None:
    table = Table(title="API Health", box=box.SIMPLE)
    table.add_column("Service", style="white")
    table.add_column("Status")
    table.add_column("Details", style="dim")

    for svc, ok in results.items():
        status = "[bold green]✓ OK[/bold green]" if ok else "[bold red]✗ FAILED[/bold red]"
        detail = "Connected" if ok else "Check key / network"
        table.add_row(svc.upper(), status, detail)

    console.print(table)
