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

from __future__ import annotations

import logging
from typing import Any, Callable

from app.llm import LLMError, chat_json

logger = logging.getLogger(__name__)


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) as exc:
        logger.warning("LLM call failed; using local fallback: %s", exc)
        return local_factory(), True, f"local ({type(exc).__name__}: {exc})"
