"""rc submit — submit a research task to the network."""

from __future__ import annotations

import json

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

console = Console()


def run(
    prompt: str = typer.Argument(..., help="Math problem description for Lean proof generation"),
    model: str = typer.Option(None, "--model", "-m", help="Override default model"),
    budget: str = typer.Option("1", "--budget", "-b", help="Credit budget for this task in TFLOP credits"),
    task_type: str = typer.Option("lean_proof_gen", "--task-type", help="Queued task type, e.g. lean_proof_gen or proof_repair"),
    metadata_json: str = typer.Option("{}", "--metadata-json", help="Optional JSON object stored with the task"),
) -> None:
    """Submit a mathematical research task for Lean code generation."""
    from rc.auth import node_auth_payload
    from rc.config import load_config
    from rc.credits import format_credit_subunits, parse_credit_amount_to_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)

    if cfg.role == "provider":
        console.print("[red]This node is configured as provider-only. Cannot submit tasks.[/red]")
        raise typer.Exit(code=1)

    model_name = model or cfg.model
    try:
        task_metadata = json.loads(metadata_json)
    except json.JSONDecodeError as exc:
        console.print(f"[red]Invalid --metadata-json value: {exc}[/red]")
        raise typer.Exit(code=1)
    if not isinstance(task_metadata, dict):
        console.print("[red]--metadata-json must decode to a JSON object.[/red]")
        raise typer.Exit(code=1)

    try:
        budget_subunits = parse_credit_amount_to_subunits(budget)
    except ValueError 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.update(
            {
                "p_prompt": prompt,
                "p_model": model_name,
                "p_budget": budget_subunits,
                "p_task_type": task_type,
                "p_task_metadata": task_metadata,
            }
        )
        resp = client.rpc(
            "submit_task",
            params,
        ).execute()
    except Exception as exc:
        error_msg = str(exc)
        if "Insufficient credits" in error_msg:
            console.print("[red]Insufficient credits for this task.[/red]")
            console.print(
                f"[yellow]Required: {format_credit_subunits(budget_subunits)} credits. "
                "Check your balance with: rc balance[/yellow]"
            )
        else:
            console.print(f"[red]Failed to submit task: {exc}[/red]")
        raise typer.Exit(code=1)

    task_id = resp.data
    if not task_id:
        console.print("[red]Failed to submit task — no task ID returned.[/red]")
        raise typer.Exit(code=1)

    console.print(
        Panel(
            f"[bold]Task ID:[/bold] {task_id}\n"
            f"[bold]Budget:[/bold]  {format_credit_subunits(budget_subunits)} credits\n"
            f"[bold]Model:[/bold]   {model_name}\n"
            f"[bold]Type:[/bold]    {task_type}",
            title="[green]Task Submitted[/green]",
            border_style="green",
        )
    )
    console.print(f"Track status: [bold]rc status {task_id}[/bold]")
