"""VP 贴纸 AI 生图 — image_gen 配置门控 + placeholder stub。"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any, Callable

from niannian.llm.spec import parse_provider_model

if TYPE_CHECKING:
    from niannian.virtual_persona.store import VirtualPersonaStore

_IMAGE_GEN_SLOTS = ("primary", "module_fallback", "global_fallback")
_DEFAULT_COUNT = 4
_MAX_COUNT = 8
_PLACEHOLDER_PNG = b"\x89PNG\r\n\x1a\n" + b"vp_sticker_gen_placeholder"


def image_gen_slot_configured(config: dict[str, Any] | None) -> bool:
    """True when api.image_gen has at least one configured provider:model slot."""
    api = (config or {}).get("api") or {}
    if not isinstance(api, dict):
        return False
    image_gen = api.get("image_gen") or {}
    if not isinstance(image_gen, dict):
        return False
    for slot in _IMAGE_GEN_SLOTS:
        if parse_provider_model(image_gen.get(slot)) is not None:
            return True
    return False


def is_image_gen_enabled(config: dict[str, Any] | None) -> bool:
    """image_gen slot configured and virtual_persona.sticker.image_gen_enabled (default true)."""
    if not image_gen_slot_configured(config):
        return False
    vp = (config or {}).get("virtual_persona") or {}
    sticker = vp.get("sticker") if isinstance(vp, dict) else {}
    if not isinstance(sticker, dict):
        return True
    return bool(sticker.get("image_gen_enabled", True))


def generate_vp_stickers(
    store: VirtualPersonaStore,
    vp_id: str,
    *,
    prompts: list[str] | None = None,
    count: int = _DEFAULT_COUNT,
    label: str = "AI表情",
    image_fn: Callable[[str], bytes] | None = None,
) -> dict[str, Any]:
    """Stub image_gen: write placeholder PNGs into VP stickers manifest."""
    from niannian.virtual_persona.stickers import add_vp_sticker_from_bytes

    limit = max(1, min(int(count), _MAX_COUNT))
    gen = image_fn or (lambda _prompt: _PLACEHOLDER_PNG)
    clean_label = str(label or "AI表情").strip()[:32] or "AI表情"

    prompts_use = [str(p).strip() for p in (prompts or []) if str(p).strip()]
    if not prompts_use:
        prompts_use = [f"{clean_label} Q版表情"] * limit
    else:
        prompts_use = prompts_use[:limit]

    stickers: list[dict[str, Any]] = []
    paths: list[str] = []
    for idx, prompt in enumerate(prompts_use):
        data = gen(prompt)
        row_label = f"{clean_label}_{idx + 1}" if len(prompts_use) > 1 else clean_label
        row = add_vp_sticker_from_bytes(
            store,
            vp_id,
            data,
            label=row_label,
            source="image_gen",
            triggers=[],
        )
        stickers.append(row)
        paths.append(str(store.vp_dir(vp_id) / "stickers" / row["file"]))

    return {
        "ok": True,
        "vp_id": vp_id,
        "count": len(stickers),
        "stickers": stickers,
        "paths": paths,
    }
