#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary.
"""Wants extractor: persists WANT/DONT_WANT items to intents table."""
import logging
from datetime import datetime, timezone

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

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


class WantsExtractor(BaseExtractor):
    """Extracts wants and dont_wants and writes them to the intents SQLite table."""

    def __init__(self):
        super().__init__('wants', 'intents')

    def extract(self, user_text: str, agent_text: str, metadata: dict) -> list:
        """Parse wants and dont_wants from conversation pair."""
        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 = []

        for want in parsed.get('wants', []):
            desc = want.get('want', '')
            if len(desc) < 15:
                continue
            priority = want.get('priority', 1)
            salience = max(1.0, float(priority))
            items.append({
                '_item_type': 'WANT',
                'type': 'intent',
                'content': desc,
                'title': desc[:80],
                'domain': domain,
                'agent': source,
                'timestamp': ts,
                'salience': salience,
                'confidence': 0.6,
            })

        for dw in parsed.get('dont_wants', []):
            desc = dw.get('dont_want', '')
            if len(desc) < 15:
                continue
            items.append({
                '_item_type': 'DONT_WANT',
                'type': 'intent',
                'content': f'[DONT_WANT] {desc}',
                'title': desc[:80],
                'domain': domain,
                'agent': source,
                'timestamp': ts,
                'salience': 2.0,
                'confidence': 0.65,
            })

        return items

    def write(self, items: list) -> int:
        """Write intent items to SQLite intents table."""
        if not items:
            return 0
        written = 0
        for item in items:
            # Strip internal marker before persisting
            record = {k: v for k, v in item.items() if not k.startswith('_')}
            try:
                from pulse.core.brain_db import insert_knowledge
                if insert_knowledge('intents', record):
                    written += 1
            except Exception as exc:
                log.debug('intents insert failed: %s', exc)
        self.extracted_count += written
        return written
