"""Shared helper: try live LLM JSON, else local deterministic generation."""

from __future__ import annotations
from typing import Any, Callable
from app.llm import LLMError, chat_json


async def generate_json(*,system: str,user: str,local_factory: Callable[[], dict[str, Any]],) -> tuple[dict[str, Any], bool, str]:
    """Returns (data, used_stub, provider_or_local)."""
    try:
        data, provider, live = await chat_json(system=system, user=user)
        if not isinstance(data, dict):
            data = {"result": data}
        return data, (not live), provider
    except (LLMError, Exception):
        return local_factory(), True, "local"
