import logging

from services.chat_prompt import get_system_prompt
from services.memory import get_all_sessions, get_history, upsert_static_system_message

logger = logging.getLogger(__name__)


async def migrate_static_system_messages() -> int:
    """Rebuild stored system rows from sessions.persona_id (strip legacy RPG text)."""
    updated = 0
    for session in await get_all_sessions():
        sid = session["session_id"]
        persona_id = session.get("persona_id") or "default"
        history = await get_history(sid)
        static = await get_system_prompt(persona_id, history, "")
        if await upsert_static_system_message(sid, static, history):
            updated += 1
    if updated:
        logger.info("Migrated %s session system message(s) to static persona prompt", updated)
    return updated
