from __future__ import annotations

from .paths import CHAR_PATH, WORLD_PATH, JOURNAL_PATH, get_core_rules_path, RULES_INJECTION_PATH
from .prompts import SYSTEM_PROMPT
from . import state


def build_system_prompt(recent_narrative: str | None = None, recent_log: str | None = None) -> str:
    """Assemble the system prompt with current game state."""
    char = state.read_file(CHAR_PATH) or "*No character sheet.*"
    world = state.truncate_world(state.read_file(WORLD_PATH) or "") or "*No world state.*"
    log = recent_log if recent_log is not None else state.read_recent_log()
    journal = state.read_file(JOURNAL_PATH) or "*No journal entries.*"
    story = recent_narrative if recent_narrative is not None else state.read_recent_book(2)
    core_rules = state.read_file(get_core_rules_path()) or "*No core rules file.*"
    extra = state.read_file(RULES_INJECTION_PATH)
    extra_section = f"\n\n## Full Mechanics Reference\n{extra}" if extra else ""
    return SYSTEM_PROMPT.substitute(
        character=char, world=world, log=log, journal=journal, story=story, core_rules=core_rules,
    ) + extra_section
