"""rc research-run — submit a backend-owned research job."""

from __future__ import annotations

import json
import urllib.error
import urllib.parse
import urllib.request

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

console = Console()


def run(
    backend_url: str | None = typer.Option(
        None,
        "--backend-url",
        envvar="RC_BACKEND_URL",
        help="Lean checker backend base URL",
    ),
    model: str = typer.Option(None, "--model", "-m", help="Override default model label stored on new tasks"),
    domain: str = typer.Option("", "--domain", help="Optional conjecture domain filter, e.g. naturals or lists"),
    max_concurrent_episodes: int = typer.Option(3, "--max-concurrent-episodes", help="Target number of active episodes"),
    budget_per_attempt: str = typer.Option("1", "--budget-per-attempt", help="Credits reserved for each attempt"),
    total_budget: str = typer.Option("25", "--total-budget", help="Total credits available to the backend-managed research job"),
    max_attempts_per_episode: int = typer.Option(4, "--max-attempts-per-episode", help="Maximum attempts per episode"),
    seed_conjecture: str = typer.Option("", "--seed-conjecture", help="Optional initial conjecture or goal text"),
    objective: str = typer.Option("autonomous_research", "--objective", help="High-level objective stored with the research job"),
) -> None:
    """Submit a backend-managed autonomous research job."""
    from rc.auth import hash_node_secret
    from rc.config import load_config, resolve_backend_url
    from rc.credits import format_credit_subunits, parse_credit_amount_to_subunits

    cfg = load_config()
    backend_url = resolve_backend_url(backend_url, cfg)
    if cfg.role == "provider":
        console.print("[red]This node is configured as provider-only. Cannot submit backend research jobs.[/red]")
        raise typer.Exit(code=1)

    try:
        total_budget_subunits = parse_credit_amount_to_subunits(total_budget)
        budget_per_attempt_subunits = parse_credit_amount_to_subunits(budget_per_attempt)
    except ValueError as exc:
        console.print(f"[red]{exc}[/red]")
        raise typer.Exit(code=1)

    payload = json.dumps(
        {
            "requester_node_id": cfg.node_id,
            "requester_secret_hash": hash_node_secret(cfg.node_secret),
            "domain": domain.strip(),
            "model": model or cfg.model,
            "total_budget": max(1, total_budget_subunits),
            "budget_per_attempt": max(1, budget_per_attempt_subunits),
            "max_concurrent_episodes": max(1, max_concurrent_episodes),
            "max_attempts_per_episode": max(1, max_attempts_per_episode),
            "seed_conjecture": seed_conjecture,
            "objective": objective,
            "metadata": {"submitted_by": cfg.node_name},
        }
    ).encode("utf-8")
    request = urllib.request.Request(
        url=f"{backend_url.rstrip('/')}/research-jobs",
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            body = json.loads(response.read().decode("utf-8"))
    except urllib.error.HTTPError as exc:
        console.print(f"[red]Backend rejected research job submission: HTTP {exc.code}[/red]")
        console.print(exc.read().decode("utf-8", errors="replace"))
        raise typer.Exit(code=1)
    except urllib.error.URLError as exc:
        console.print(f"[red]Failed to contact backend: {exc.reason}[/red]")
        raise typer.Exit(code=1)

    console.print(
        Panel(
            f"[bold]Job ID:[/bold] {body['job_id']}\n"
            f"[bold]Backend:[/bold] {backend_url}\n"
            f"[bold]Total Budget:[/bold] {format_credit_subunits(total_budget_subunits)} credits\n"
            f"[bold]Per Attempt:[/bold] {format_credit_subunits(budget_per_attempt_subunits)} credits\n"
            f"[bold]Model:[/bold] {model or cfg.model}",
            title="[green]Research Job Submitted[/green]",
            border_style="green",
        )
    )
    console.print(f"Track progress: [bold]rc research-status {body['job_id']} --backend-url {backend_url}[/bold]")
