from __future__ import annotations

from typing import List, Optional

from analogai.deepthink.presentation.preprocessing.previous_messages_stack import PreviousMessagesStack


class QuestionHistoryFormatter:
    def format_qa_history(self, stack: Optional[PreviousMessagesStack]) -> str:
        if stack is None:
            return ""
        pairs = list(stack.get_history_pairs())[-10:]
        if not pairs:
            return ""
        lines: List[str] = []
        for role, text in pairs:
            if not text:
                continue
            label = "Q" if role == "user" else "A"
            lines.append(f"{label}: {text}")
        return "\n".join(lines)

    def format_user_history(self, stack: Optional[PreviousMessagesStack]) -> str:
        if stack is None:
            return ""
        pairs = list(stack.get_history_pairs())[-10:]
        if not pairs:
            return ""
        user_texts: List[str] = []
        for role, text in pairs:
            if role != "user" or not text:
                continue
            cleaned = text.strip()
            if cleaned and "?" not in cleaned:
                user_texts.append(cleaned)
        if not user_texts:
            return ""
        return ". ".join(user_texts)
