"""Supabase connection singleton."""

from __future__ import annotations

from functools import lru_cache

from supabase import Client, create_client

from rc.auth import generate_node_secret, hash_node_secret
from rc.config import load_config, save_config


@lru_cache(maxsize=1)
def get_client() -> Client:
    cfg = load_config()
    if not cfg.supabase_url or not cfg.supabase_key:
        raise RuntimeError(
            "Supabase credentials not configured. Run 'rc init' first."
        )
    client = create_client(cfg.supabase_url, cfg.supabase_key)
    if cfg.node_id and not cfg.node_secret:
        cfg.node_secret = generate_node_secret()
        save_config(cfg)
        client.rpc(
            "register_node",
            {
                "p_id": cfg.node_id,
                "p_name": cfg.node_name,
                "p_role": cfg.role,
                "p_public_key": "",
                "p_auth_token_hash": hash_node_secret(cfg.node_secret),
                "p_gpu_info": cfg.gpu_info_payload(),
            },
        ).execute()
    return client
