"""rc research-status — inspect research episodes and proof attempts."""

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
from rich.table import Table

console = Console()


def run(
    episode_id: str | None = typer.Argument(None, help="Optional research episode ID to inspect"),
    backend_url: str | None = typer.Option(
        None,
        "--backend-url",
        envvar="RC_BACKEND_URL",
        help="Backend base URL",
    ),
    limit: int = typer.Option(10, "--limit", help="Number of episodes to list when no ID is provided"),
) -> None:
    """Inspect backend-managed research jobs."""
    from rc.auth import hash_node_secret
    from rc.config import load_config, resolve_backend_url

    cfg = load_config()
    backend_url = resolve_backend_url(backend_url, cfg)
    auth = {
        "requester_node_id": cfg.node_id,
        "requester_secret_hash": hash_node_secret(cfg.node_secret),
    }

    if episode_id:
        query = urllib.parse.urlencode(auth)
        try:
            with urllib.request.urlopen(
                f"{backend_url.rstrip('/')}/research-jobs/{episode_id}?{query}",
                timeout=30,
            ) as response:
                payload = json.loads(response.read().decode("utf-8"))
        except urllib.error.URLError as exc:
            console.print(f"[red]Failed to contact backend: {exc.reason}[/red]")
            raise typer.Exit(code=1)
        if not payload:
            console.print(f"[red]Research job {episode_id} not found.[/red]")
            raise typer.Exit(code=1)
        _render_job(payload)
        return

    query = urllib.parse.urlencode({**auth, "limit": max(1, limit)})
    try:
        with urllib.request.urlopen(f"{backend_url.rstrip('/')}/research-jobs?{query}", timeout=30) as response:
            jobs = json.loads(response.read().decode("utf-8"))
    except urllib.error.URLError as exc:
        console.print(f"[red]Failed to contact backend: {exc.reason}[/red]")
        raise typer.Exit(code=1)
    if not jobs:
        console.print("[yellow]No research jobs found.[/yellow]")
        return

    table = Table(title="Research Jobs")
    table.add_column("Job")
    table.add_column("Status")
    table.add_column("Domain")
    table.add_column("Budget", justify="right")
    table.add_column("Committed", justify="right")
    table.add_column("Concurrency", justify="right")
    table.add_column("Seed")
    for job in jobs:
        table.add_row(
            f"{job['id'][:8]}...",
            job.get("status", "unknown"),
            job.get("domain", "-") or "-",
            f"{int(job.get('total_budget', 0)):,}",
            f"{int(job.get('credits_committed', 0)):,}",
            str(job.get("max_concurrent_episodes", 1)),
            str(job.get("seed_conjecture", ""))[:60],
        )
    console.print(table)


def _render_job(job: dict) -> None:
    console.print(
        Panel(
            f"[bold]Status:[/bold] {job.get('status', 'unknown')}\n"
            f"[bold]Objective:[/bold] {job.get('objective', '-')}\n"
            f"[bold]Domain:[/bold] {job.get('domain', '-') or '-'}\n"
            f"[bold]Budget:[/bold] {int(job.get('credits_committed', 0)):,}/{int(job.get('total_budget', 0)):,}\n"
            f"[bold]Concurrency:[/bold] {job.get('max_concurrent_episodes', 1)}\n"
            f"[bold]Seed:[/bold] {job.get('seed_conjecture', '') or '-'}",
            title=f"Job {job['id'][:12]}...",
        )
    )

    attempts_table = Table(title="Proof Attempts")
    attempts_table.add_column("Attempt")
    attempts_table.add_column("Status")
    attempts_table.add_column("Task Type")
    attempts_table.add_column("Provider")
    attempts_table.add_column("Summary")
    for episode in job.get("episodes", []):
        for attempt in episode.get("attempts", []):
            attempts_table.add_row(
                f"{episode['id'][:4]}:{attempt.get('attempt_index', '?')}",
                attempt.get("verification_status", "pending"),
                attempt.get("task_type", "proof_attempt"),
                str(attempt.get("provider_id", "") or "-")[:8],
                str(attempt.get("verification_summary") or attempt.get("lean_stderr") or "pending")[:90],
            )
    console.print(attempts_table)
