"""rc ledger — view recent transaction history."""

from __future__ import annotations

import typer
from rich.console import Console
from rich.table import Table

console = Console()


def _direction_for_row(row: dict, node_id: str) -> str:
    txn_type = row.get("type", "")
    from_id = row.get("from_node_id")
    to_id = row.get("to_node_id")

    if txn_type == "reserve":
        return "[yellow]-HELD[/yellow]"
    if txn_type == "release":
        return "[green]+FREE[/green]"
    if txn_type == "transfer":
        if to_id == node_id and from_id == node_id:
            return "[cyan]SELF[/cyan]"
        if to_id == node_id:
            return "[green]+IN[/green]"
        if from_id == node_id:
            return "[red]-OUT[/red]"
    if txn_type in {"mint", "refund"}:
        return "[green]+IN[/green]"
    if txn_type == "burn":
        return "[red]-OUT[/red]"
    return "[white]INFO[/white]"


def run(
    limit: int = typer.Option(20, "--limit", "-l", help="Number of transactions to show"),
) -> None:
    """Show recent Compute Credit transactions for this node."""
    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()
        params = node_auth_payload(cfg)
        params["p_limit"] = limit
        resp = client.rpc("get_ledger", params).execute()
    except Exception as exc:
        console.print(f"[red]Failed to fetch transactions: {exc}[/red]")
        raise typer.Exit(code=1)

    rows = resp.data
    if not rows:
        console.print("[dim]No transactions found.[/dim]")
        return

    table = Table(
        title=f"Transaction Ledger — {cfg.node_name} ({cfg.node_id[:8]}...)",
        show_lines=True,
    )
    table.add_column("Time", style="dim", width=19)
    table.add_column("Type", style="bold", width=10)
    table.add_column("Amount", justify="right", width=14)
    table.add_column("Direction", width=10)
    table.add_column("Task", style="dim", width=10)
    table.add_column("Memo")

    for row in rows:
        direction = _direction_for_row(row, cfg.node_id)
        task_short = (row.get("task_id") or "")[:8] or "—"
        table.add_row(
            str(row.get("created_at", ""))[:19],
            row.get("type", ""),
            f"{format_credit_subunits(row.get('amount', 0))}",
            direction,
            task_short,
            row.get("memo", "") or "",
        )

    console.print(table)
