#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary.
"""Knowledge extractor: routes lessons/failures/patterns via bridge pipeline."""
import logging
from datetime import datetime, timezone

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

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


class KnowledgeExtractor(BaseExtractor):
    """Wraps the bridge routing pipeline for LEARNING/FAILURE/PATTERN items."""

    def __init__(self):
        super().__init__('knowledge', 'lessons')

    def extract(self, user_text: str, agent_text: str, metadata: dict) -> list:
        """Parse wants/dont_wants and convert to knowledge items."""
        try:
            from pulse.brain.extraction.wants_parser import parse_full
        except ImportError:
            return []

        try:
            parsed = parse_full(user_text, agent_text)
        except Exception as exc:
            log.debug('wants parse failed: %s', exc)
            return []

        ts = metadata.get('timestamp', datetime.now(timezone.utc).isoformat())
        domain = parsed.get('primary_domain', 'general')
        source = metadata.get('source', 'distiller')
        items = []

        # High-priority wants become LEARNING items
        for want in parsed.get('wants', []):
            if want.get('priority', 0) >= 2 and len(want.get('want', '')) > 15:
                items.append({
                    'type': 'LEARNING',
                    'description': want['want'],
                    'domain': domain,
                    'timestamp': ts,
                    'confidence': 0.6,
                    'salience': float(want.get('priority', 2)),
                    '_source': source,
                })

        # Explicit rejections become FAILURE items
        for dw in parsed.get('dont_wants', []):
            desc = dw.get('dont_want', '')
            if len(desc) > 15:
                items.append({
                    'type': 'FAILURE',
                    'description': desc,
                    'domain': domain,
                    'timestamp': ts,
                    'confidence': 0.65,
                    'salience': 2.0,
                    '_source': source,
                })

        return items

    def write(self, items: list) -> int:
        """Route items through bridge knowledge routing (JSONL + SQLite)."""
        if not items:
            return 0
        try:
            from pulse.daemons.bridge.bridge_routing import route_knowledge
            from pulse.brain.save_writers.quality import _passes_quality_gate
        except ImportError:
            return 0

        gated = [
            it for it in items
            if _passes_quality_gate(
                it.get('description', ''),
                it.get('salience', 0.0),
                it.get('confidence', 0.0),
            )
        ]
        if not gated:
            return 0

        source = gated[0].get('_source', 'distiller') if gated else 'distiller'
        try:
            route_knowledge(gated, source)
        except Exception as exc:
            log.debug('route_knowledge failed: %s', exc)
            return 0

        self.extracted_count += len(gated)
        return len(gated)
