"""Backend-facing research job RPC helpers."""

from __future__ import annotations

from typing import Any

from backend.supabase_runtime import get_supabase_client


def submit_research_job(payload: dict[str, Any]) -> str:
    response = get_supabase_client().rpc("submit_research_job", payload).execute()
    job_id = response.data
    if not job_id:
        raise RuntimeError("submit_research_job did not return a job id")
    return job_id


def get_research_job(job_id: str, requester_node_id: str, requester_secret_hash: str) -> dict[str, Any] | None:
    response = get_supabase_client().rpc(
        "get_research_job",
        {
            "p_job_id": job_id,
            "p_node_id": requester_node_id,
            "p_node_secret_hash": requester_secret_hash,
        },
    ).execute()
    return response.data


def list_research_jobs(requester_node_id: str, requester_secret_hash: str, limit: int = 20) -> list[dict[str, Any]]:
    response = get_supabase_client().rpc(
        "list_research_jobs",
        {
            "p_node_id": requester_node_id,
            "p_node_secret_hash": requester_secret_hash,
            "p_limit": limit,
            "p_status": None,
        },
    ).execute()
    return response.data or []
