"""rc rotate-secret — rotate the local node bearer secret."""

from __future__ import annotations

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

from rc.auth import generate_node_secret, hash_node_secret
from rc.config import load_config, save_config
from rc.supabase_client import get_client

console = Console()


def run() -> None:
    """Rotate the current node secret and persist the new value locally."""
    try:
        cfg = load_config()
    except FileNotFoundError as exc:
        console.print(f"[red]{exc}[/red]")
        raise typer.Exit(code=1)

    if not cfg.node_id or not cfg.node_secret:
        console.print("[red]This node does not have a local secret to rotate.[/red]")
        raise typer.Exit(code=1)

    client = get_client()
    new_secret = generate_node_secret()

    try:
        resp = client.rpc(
            "rotate_node_secret",
            {
                "p_node_id": cfg.node_id,
                "p_current_secret_hash": hash_node_secret(cfg.node_secret),
                "p_new_secret_hash": hash_node_secret(new_secret),
            },
        ).execute()
    except Exception as exc:
        console.print(f"[red]Secret rotation failed: {exc}[/red]")
        raise typer.Exit(code=1)

    if not resp.data:
        console.print("[red]Secret rotation was rejected by the server.[/red]")
        raise typer.Exit(code=1)

    cfg.node_secret = new_secret
    save_config(cfg)

    console.print(
        Panel(
            f"[bold]Node:[/bold] {cfg.node_name} ({cfg.node_id[:8]}...)\n"
            "[bold]Status:[/bold] node secret rotated successfully",
            title="[green]Secret Rotated[/green]",
            border_style="green",
        )
    )
