from services.personas import get_persona
from services.lorebook import get_lorebook_context
from services.character_card import get_character

DEFAULT_PROMPT = "Ты — полезный AI ассистент. Отвечай чётко и по делу."

from services.rp_sanitize import ROLEPLAY_GUARDRAILS  # noqa: E402 — re-export for imports


async def get_system_prompt(persona_id: str, history: list, user_message: str = "") -> str:
    """Static character prompt only (no RPG runtime blocks)."""
    persona = await get_persona(persona_id)
    if not persona:
        return DEFAULT_PROMPT
    prompt = persona["prompt"]
    recent = [m for m in history if m["role"] in ("user", "assistant")][-5:]
    context = recent + [{"role": "user", "content": user_message}]
    if persona.get("lorebook_json"):
        lore = get_lorebook_context(persona.get("lorebook_json", "[]"), context)
        if lore:
            prompt += "\n\n" + lore
    if persona_id.startswith("card_"):
        card = await get_character(persona_id[5:])
        if card:
            lore = get_lorebook_context(card.get("lorebook_json", "[]"), context)
            if lore:
                prompt += "\n\n" + lore
    if persona_id != "default":
        prompt += "\n\n" + ROLEPLAY_GUARDRAILS
    return prompt
