#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary.
"""Fact extractor: detects and stores declarative facts."""
import logging

from pulse.daemons.distiller.extractors.base import BaseExtractor

log = logging.getLogger('pulse.distiller.facts')


class FactExtractor(BaseExtractor):
    """Extracts declarative facts (infrastructure, services, identities) and persists them."""

    def __init__(self):
        super().__init__('facts', 'facts')

    def extract(self, user_text: str, agent_text: str, metadata: dict) -> list:
        """Parse facts from combined conversation text."""
        try:
            from pulse.brain.extraction.fact_parser import parse_facts
        except ImportError:
            return []

        combined = user_text + '\n' + agent_text if agent_text else user_text
        try:
            facts = parse_facts(combined)
        except Exception as exc:
            log.debug('fact_parser failed: %s', exc)
            return []

        source = metadata.get('source', 'distiller')
        for fact in facts:
            fact.setdefault('_source', source)

        return facts or []

    def write(self, items: list) -> int:
        """Delegate to fact_store which handles dedup and temporal tracking."""
        if not items:
            return 0
        try:
            from pulse.brain.persistence.fact_store import store_facts
        except ImportError:
            return 0

        source = items[0].get('_source', 'distiller') if items else 'distiller'
        # Strip internal markers before passing to store_facts
        clean = [{k: v for k, v in it.items() if not k.startswith('_')} for it in items]
        try:
            stored = store_facts(clean, source=source)
        except Exception as exc:
            log.debug('store_facts failed: %s', exc)
            return 0
        stored = stored if isinstance(stored, int) else len(clean)
        self.extracted_count += stored
        return stored
