from typing import List
from .playbooks.store import playbook_store, PlaybookItem


def _all() -> List[PlaybookItem]:
    """Return all playbooks sorted by order (position 0 is always main)."""
    return playbook_store.all_playbooks()


def get_main_playbook() -> PlaybookItem | None:
    playbooks = _all()
    return playbooks[0] if playbooks else None


def get_context_playbooks() -> List[PlaybookItem]:
    """All playbooks after the first — injected as reference context."""
    playbooks = _all()
    return playbooks[1:] if len(playbooks) > 1 else []


def get_system_prompt() -> str:
    playbook = get_main_playbook()
    if not playbook:
        return ""
    goal = (getattr(playbook, "goal", "") or "").strip()
    instructions = (getattr(playbook, "instructions", "") or "").strip()
    if goal and instructions:
        return f"{goal}\n\n{instructions}"
    return goal or instructions
