from __future__ import annotations

from typing import Optional

from analogai.deepthink.messaging.fact.fact import Fact


def format_fact_summary(fact: Fact) -> str:
    text = fact.text.strip() if fact.text else ""
    if text:
        return f"source={fact.user_id}: {text}"
    return f"source={fact.user_id}"


def get_belief_id(belief) -> Optional[str]:
    if belief is None:
        return None
    value = belief.id
    return str(value) if value else None


def get_statement_id(belief) -> Optional[str]:
    if belief is None:
        return None
    value = belief.statement_id
    return str(value) if value else None


def get_fact_text(fact) -> str:
    if fact is None:
        return ""
    return str(fact.text or "")


def collect_fact_window(fact, window: int) -> list:
    if fact is None:
        return []
    prevs: list = []
    current = fact
    for _ in range(max(0, int(window))):
        prev_chunk = current.prev()
        if prev_chunk is None:
            break
        prevs.append(prev_chunk)
        current = prev_chunk
    nexts: list = []
    current = fact
    for _ in range(max(0, int(window))):
        next_chunk = current.next()
        if next_chunk is None:
            break
        nexts.append(next_chunk)
        current = next_chunk
    prevs.reverse()
    return prevs + [fact] + nexts
