"""Supabase persistence for verified Lean lemmas."""

from __future__ import annotations

from typing import Any

from backend.supabase_runtime import get_supabase_client, supabase_is_configured


def store_verified_lemma(payload: dict[str, Any]) -> str:
    """Persist a verified lemma row in Supabase and return its id."""
    if not supabase_is_configured():
        raise RuntimeError(
            "Supabase is not configured. Set SUPABASE_URL and either "
            "SUPABASE_SERVICE_ROLE_KEY or SUPABASE_KEY."
        )

    params = {
        "p_source_task_id": str(payload.get("source_task_id") or ""),
        "p_source_prompt": str(payload.get("source_prompt") or ""),
        "p_metadata": payload.get("metadata") or {},
        "p_conjecture": str(payload.get("conjecture") or ""),
        "p_normalized_code": str(payload.get("normalized_code") or ""),
        "p_verification_status": str(payload.get("verification_status") or ""),
        "p_verification_summary": str(payload.get("verification_summary") or ""),
        "p_compiler": str(payload.get("compiler") or ""),
        "p_stdout": str(payload.get("stdout") or ""),
        "p_stderr": str(payload.get("stderr") or ""),
        "p_is_true": bool(payload.get("is_true")),
    }
    response = get_supabase_client().rpc("store_verified_lemma", params).execute()
    lemma_id = response.data
    if not lemma_id:
        raise RuntimeError("Supabase did not return a verified lemma id.")
    return str(lemma_id)
