"""Production install plans load the pinned discovery recipe before compile."""

from __future__ import annotations

from src.domain.app_blocks.compiler import PINNED_EMPTY_RECIPE, compile_install_plan
from src.domain.app_blocks.schemas import AppBlockPlan
from src.domain.composition_recipes.service import CompositionRecipeService


async def pinned_recipe_for_state(
    db,
    state: dict | None,
    *,
    source_prompt: str,
    project_type: str | None = None,
):
    """Return the recipe a production compile must use.

    A pinned null slug is ``PINNED_EMPTY_RECIPE`` so YAML matching stays off.
    Unpinned legacy states still resolve from the prompt and may be None.
    """
    state = state or {}
    service = CompositionRecipeService(db)
    if state.get("composition_recipe_pinned"):
        slug = state.get("composition_recipe_slug")
        if not slug:
            return PINNED_EMPTY_RECIPE
        recipe = await service.get(slug)
        return recipe if recipe is not None else PINNED_EMPTY_RECIPE
    return await service.resolve_for_text(source_prompt, project_type)


async def compile_pinned_install_plan(
    db,
    state: dict | None,
    spec,
    *,
    source_prompt: str = "",
    project_type: str | None = None,
    **kwargs,
) -> AppBlockPlan:
    recipe = await pinned_recipe_for_state(
        db, state, source_prompt=source_prompt, project_type=project_type
    )
    if recipe is not None:
        kwargs["composition_recipe"] = recipe
    return compile_install_plan(spec, source_prompt=source_prompt, **kwargs)
