"""rc balance — view current compute credit balance."""

from __future__ import annotations

import typer
from rich.console import Console
from rich.panel import Panel

console = Console()


def _humanize_credits(value: int) -> str:
    from rc.credits import credit_subunits_to_decimal

    tflops = float(credit_subunits_to_decimal(value))
    if tflops >= 1_000_000:
        return f"{tflops / 1_000_000:.3f} EFLOP"
    if tflops >= 1_000:
        return f"{tflops / 1_000:.3f} PFLOP"
    return f"{tflops:.6f} TFLOP"


def run() -> None:
    """Display your current Compute Credit balance."""
    from rc.auth import node_auth_payload
    from rc.config import load_config
    from rc.credits import format_credit_subunits
    from rc.supabase_client import get_client

    try:
        cfg = load_config()
    except FileNotFoundError as exc:
        console.print(f"[red]{exc}[/red]")
        raise typer.Exit(code=1)

    try:
        client = get_client()
        if not cfg.node_secret:
            cfg = load_config()
        resp = client.rpc("get_balance", node_auth_payload(cfg)).execute()
    except Exception as exc:
        console.print(f"[red]Failed to fetch balance: {exc}[/red]")
        raise typer.Exit(code=1)

    rows = resp.data or []
    if not rows:
        console.print("[red]No balance record found for this node.[/red]")
        raise typer.Exit(code=1)

    row = rows[0]
    bal = row.get("balance", 0)
    reserved = row.get("reserved_balance", 0)
    total = row.get("total_balance", bal + reserved)
    updated = str(row.get("updated_at", "N/A"))[:19]

    console.print(
        Panel(
            f"[bold cyan]Available:[/bold cyan] {format_credit_subunits(bal)} credits  ({_humanize_credits(bal)})\n"
            f"[bold yellow]Reserved:[/bold yellow]  {format_credit_subunits(reserved)} credits  ({_humanize_credits(reserved)})\n"
            f"[bold]Total:[/bold]     {format_credit_subunits(total)} credits  ({_humanize_credits(total)})\n"
            f"[dim]Last updated: {updated}[/dim]",
            title=f"[bold]{cfg.node_name}[/bold] ({cfg.node_id[:8]}...)",
            border_style="cyan",
        )
    )
