from __future__ import annotations

from typing import Iterable, List, Optional

from analogai.deepthink.messaging.fact.services.fact_context_service import FactContextWindowService
from analogai.foundation.common.logging.app_logger import app_logger
from analogai.deepthink.messaging.text.sentence_chunker import split_into_sentences


class AnswerFactAssembler:
    def __init__(self, fact_context_service: Optional[FactContextWindowService] = None) -> None:
        self._fact_context_service = fact_context_service

    def build_fact_block(
        self,
        beliefs: Iterable,
        belief_lines: Iterable[str],
        notion_lines: Iterable[str],
        fact_lookup: dict[str, str],
        raw_answer: str,
        qa_history: str,
        user_history_block: str,
        include_raw_answer: bool = True,
    ) -> str:
        items: List[str] = []
        if fact_lookup:
            for fact_key, fact_text in fact_lookup.items():
                cleaned = _sanitize_fact_line(fact_text)
                if not cleaned:
                    continue
                try:
                    app_logger.debug(
                        "[AnswerFactAssembler] fact added to facts id=%s value=%s",
                        fact_key,
                        cleaned,
                    )
                except Exception:
                    pass
                _extend_fact_items(items, cleaned)
        if not items:
            return ""
        return "\n".join(f"{index}) {item}" for index, item in enumerate(items, start=1))


def _looks_like_question(text: str) -> bool:
    if "?" in text:
        return True
    lowered = text.strip().lower()
    return lowered.startswith("q:") or lowered.startswith("question:")


def _sanitize_fact_line(text: str) -> str:
    if not text:
        return ""
    cleaned = str(text).strip()
    if "A:" in cleaned:
        cleaned = cleaned.rsplit("A:", 1)[-1].strip()
        cleaned = cleaned.lstrip("|-–— ")
    if not cleaned:
        return ""
    if _looks_like_question(cleaned):
        return ""
    return cleaned


def _normalize_fact_line(text: str) -> str:
    normalized = text.strip().lower()
    if normalized.startswith("-"):
        normalized = normalized.lstrip("- ")
    return normalized


def _append_fact_item(items: List[str], item: str) -> None:
    items.append(item)


def _extend_fact_items(items: List[str], text: str) -> None:
    sentences = split_into_sentences(text)
    if not sentences:
        _append_fact_item(items, text)
        return
    for sentence in sentences:
        cleaned = sentence.strip()
        if not cleaned:
            continue
        _append_fact_item(items, cleaned)
