"""rc status — check the status and results of a task."""

from __future__ import annotations

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

console = Console()

STATUS_STYLE = {
    "pending": ("yellow", "Waiting for a provider..."),
    "assigned": ("blue", "Claimed by a provider"),
    "running": ("cyan", "Inference in progress"),
    "completed": ("green", "Finished"),
    "failed": ("red", "Failed"),
}


def run(
    task_id: str = typer.Argument(..., help="Task ID to check"),
) -> None:
    """Check the status of a submitted task."""
    from rc.auth import node_auth_payload
    from rc.config import load_config
    from rc.credits import format_credit_subunits
    from rc.inference.flops import FLOPS_PER_MFLOP, format_flops_as_tflops
    from rc.supabase_client import get_client

    try:
        cfg = load_config()
        client = get_client()
        if not cfg.node_secret:
            cfg = load_config()
    except (FileNotFoundError, RuntimeError) as exc:
        console.print(f"[red]{exc}[/red]")
        raise typer.Exit(code=1)

    try:
        params = node_auth_payload(cfg)
        params["p_task_id"] = task_id
        task_resp = client.rpc("get_task", params).execute()
    except Exception as exc:
        console.print(f"[red]Task not found or query failed: {exc}[/red]")
        raise typer.Exit(code=1)

    task = task_resp.data
    if not task:
        console.print(f"[red]Task {task_id} not found.[/red]")
        raise typer.Exit(code=1)

    color, label = STATUS_STYLE.get(task["status"], ("white", task["status"]))

    console.print(
        Panel(
            f"[bold]Status:[/bold]  [{color}]{task['status']}[/{color}] — {label}\n"
            f"[bold]Type:[/bold]    {task.get('type', 'lean_proof_gen')}\n"
            f"[bold]Model:[/bold]   {task.get('model', 'N/A')}\n"
            f"[bold]Budget:[/bold]  {format_credit_subunits(task.get('credit_budget', 0))} credits\n"
            f"[bold]Episode:[/bold] {str(task.get('research_episode_id') or 'N/A')[:12]}\n"
            f"[bold]Episode Attempt:[/bold] {task.get('attempt_index', 0)}\n"
            f"[bold]Attempts:[/bold] {task.get('attempt_count', 0)}/{task.get('max_attempts', 3)}\n"
            f"[bold]Created:[/bold] {str(task.get('created_at', 'N/A'))[:19]}",
            title=f"Task {task_id[:12]}...",
            border_style=color,
        )
    )

    if task.get("last_error") and task["status"] != "completed":
        console.print(f"[yellow]Last error: {task['last_error']}[/yellow]")

    if task.get("episode"):
        episode = task["episode"]
        console.print(
            f"[dim]Episode status: {episode.get('status', 'N/A')} | "
            f"domain={episode.get('domain', '-') or '-'} | "
            f"interestingness={episode.get('interestingness_score', 0):.1f} | "
            f"novelty={episode.get('novelty_score', 0):.1f}[/dim]"
        )

    if task.get("proof_attempt"):
        attempt = task["proof_attempt"]
        console.print(
            f"[dim]Proof attempt verification: {attempt.get('verification_status', 'pending')} | "
            f"{attempt.get('verification_summary', 'verification pending')}[/dim]"
        )

    if task["status"] == "completed":
        result = task.get("result")

        if result and result.get("lean_code"):
            console.print(
                Panel(
                    Syntax(result["lean_code"], "lean", theme="monokai", line_numbers=True),
                    title="Generated Lean 4 Code",
                    border_style="green",
                )
            )
            actual_flops = int(
                result.get("flops_used", int(result.get("mflops_used", 0) or 0) * FLOPS_PER_MFLOP) or 0
            )
            console.print(f"  [dim]Actual compute: {format_flops_as_tflops(actual_flops)} TFLOPs[/dim]")
            console.print(f"  [dim]Raw FLOPs:     {actual_flops}[/dim]")
            console.print(
                f"  [dim]Billed credits: {format_credit_subunits(int(result.get('billed_mflops', 0) or 0))}[/dim]"
            )
            console.print(
                f"  [dim]Tokens:        {result.get('prompt_tokens', 0)} prompt / "
                f"{result.get('generated_tokens', 0)} generated[/dim]"
            )
            console.print(
                f"  [dim]Eval time:     {result.get('total_eval_ms', 0.0):.2f} ms[/dim]"
            )
            console.print(f"  [dim]Provider:      {result.get('provider_id', 'N/A')[:8]}...[/dim]")
    elif task["status"] == "failed":
        console.print("[yellow]The task failed during inference. You can resubmit.[/yellow]")
