#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary.
"""Session extractor: LLM-powered session boundary summariser."""
import logging
from datetime import datetime, timezone
from typing import List, Tuple

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


class SessionExtractor:
    """Called at session boundaries (30-min gap) to produce a session summary."""

    def __init__(self):
        self.summarized_count = 0

    def summarize(self, turns: List[Tuple], metadata: dict) -> bool:
        """Summarise a completed session using LLM and persist to SQLite + episodic table.

        Args:
            turns: list of (datetime, user_text, agent_text) tuples.
            metadata: dict with at least 'source' and 'domain' keys.

        Returns:
            True if summary was saved, False on failure or insufficient content.
        """
        if not turns:
            return False

        combined_parts = []
        for ts, user_t, agent_t in turns:
            if user_t:
                combined_parts.append(f'USER: {user_t[:500]}')
            if agent_t:
                combined_parts.append(f'AGENT: {agent_t[:500]}')
        combined = '\n'.join(combined_parts)

        if len(combined.strip()) < 50:
            return False

        source = metadata.get('source', 'distiller')
        domain = metadata.get('domain', 'general')
        first_ts = turns[0][0]
        ts_iso = (
            first_ts.isoformat()
            if hasattr(first_ts, 'isoformat')
            else datetime.now(timezone.utc).isoformat()
        )

        summary_data = self._llm_summarize(combined, domain)
        if not summary_data:
            return False

        summary = summary_data.get('summary', '')
        if not summary or len(summary) < 15:
            return False

        key_decisions = summary_data.get('key_decisions', [])
        key_discoveries = summary_data.get('key_discoveries', [])
        files_touched = summary_data.get('files_touched', [])
        user_intent = summary_data.get('user_intent', '')

        # Record session lifecycle
        session_id = ''
        try:
            from pulse.brain.session.session_lifecycle import start_session, record_turn, end_session
            session_id = start_session(agent=source, task=user_intent[:100], domain=domain)
            for turn_ts, user_t, agent_t in turns:
                if user_t:
                    record_turn(session_id, 'user', user_t, domain=domain, timestamp=turn_ts.isoformat() if hasattr(turn_ts, 'isoformat') else ts_iso)
                if agent_t:
                    record_turn(session_id, 'agent', agent_t, domain=domain, timestamp=turn_ts.isoformat() if hasattr(turn_ts, 'isoformat') else ts_iso)
            end_session(
                session_id,
                summary=summary,
                user_intent=user_intent,
                key_decisions=key_decisions,
                key_discoveries=key_discoveries,
                files_touched=files_touched,
            )
        except Exception as exc:
            log.debug('session lifecycle failed: %s', exc)

        # Save episodic memory — one entry per session
        try:
            from pulse.brain.index.episodic_writer import save_episode
            key_events = key_decisions + key_discoveries
            save_episode(
                agent=source,
                session_summary=summary,
                key_events=key_events[:10],
                domain=domain,
                session_id=session_id,
                timestamp=ts_iso,
            )
        except Exception as exc:
            log.debug('save_episode failed: %s', exc)

        self.summarized_count += 1
        return True

    def _llm_summarize(self, text: str, domain: str) -> dict:
        """Call LLM to produce structured session summary."""
        try:
            from pulse.core.llm_router import dispatch_json
        except ImportError:
            return {}

        prompt = (
            'Summarise this AI conversation session. Return ONLY valid JSON:\n'
            '{\n'
            '  "summary": "2-3 sentence overview",\n'
            '  "user_intent": "main goal in one sentence",\n'
            '  "key_decisions": ["decision 1", "decision 2"],\n'
            '  "key_discoveries": ["finding 1", "finding 2"],\n'
            '  "files_touched": ["path/to/file.py"]\n'
            '}\n\n'
            f'DOMAIN: {domain}\n\nCONVERSATION:\n{text[:4000]}'
        )
        try:
            result = dispatch_json(prompt=prompt, task_type='premium')
        except Exception as exc:
            log.debug('LLM summarize failed: %s', exc)
            return {}

        if not isinstance(result, dict):
            return {}
        return result
