from __future__ import annotations

from analogai.foundation.core.observables.statement_observable_service import StatementObserver
from analogai.foundation.modules.fact.services.fact_service import FactServicePort
from analogai.foundation.modules.fact.subscribers.fact_observer_registry import (
    FactObserverRegistry,
)


class StatementFactSubscriber(StatementObserver):
    def __init__(self, fact_service: FactServicePort, registry: FactObserverRegistry) -> None:
        self._fact_service = fact_service
        self._registry = registry

    def append_current_sentence(self, text: str, source: object, role: str = "user") -> None:
        self._registry.append_current_sentence(text=text, role=role, source=source)

    def on_statement_created(self, statement) -> None:
        context = self._registry.get_current_sentence()
        if context is None or not context.text or not context.text.strip():
            if self._registry.require_sentence:
                raise ValueError("Fact observer requires current sentence text")
            return
        self._fact_service.record_direct_statement_fact(
            user_id=statement.user_id,
            agent_id=statement.agent_id,
            statement_id=str(statement.id),
            text=context.text,
            role=context.role,
            user_name=context.user_name,
            timestamp=context.timestamp,
            source=context.source,
        )

    def on_statement_updated(self, statement) -> None:
        return


__all__ = ["StatementFactSubscriber"]
