"""
Layer 1 summarization for session compression.

Optional local model summarization for large sessions (>1M tokens).
Uses Ollama for local inference (zero API cost).

Reference: RFC-002-R1 §3.2 Layer 1: Small Model Summarization
"""

from __future__ import annotations

import json
import logging
from typing import TYPE_CHECKING

from returns.result import Failure, Result, Success

from lattice.core.types.event import estimate_tokens, should_summarize

if TYPE_CHECKING:
    from lattice.core.types.config import Layer1Config
    from lattice.core.types.event import Event

logger = logging.getLogger(__name__)

SUMMARIZE_PROMPT = """You are a session summarizer for a coding agent.
Summarize the following session events into a concise summary that captures:
1. Key decisions made
2. Trade-offs discussed
3. Files modified
4. Errors encountered and resolved

Keep the summary under 500 tokens. Focus on what matters for future context.

Events:
{events}

Summary:"""


# @invar:allow shell_complexity: Ollama API integration with multiple error handling branches
# @shell_complexity: Ollama API integration with multiple error handling branches
def layer1_summarize(
    events: list[Event],
    config: Layer1Config,
) -> Result[str, str]:
    """Summarize events using local Ollama model.

    Only called when config.enabled=True and session exceeds min_tokens.

    Args:
        events: List of events to summarize.
        config: Layer1 configuration.

    Returns:
        Success with summary text, or Failure with error message.

    Example:
        >>> from lattice.core.types.config import Layer1Config
        >>> from lattice.core.types.event import Event, EventType
        >>> config = Layer1Config(enabled=True)
        >>> events = [Event(type=EventType.USER, content="Hello")]
        >>> result = layer1_summarize(events, config)  # doctest: +SKIP
    """
    if not config.enabled:
        logger.debug("Layer 1 summarization disabled")
        return Failure("Layer 1 summarization is disabled")

    try:
        import requests
    except ImportError:
        logger.warning("requests library not installed, cannot use Layer 1")
        return Failure("requests library not installed")

    # Format events for summarization
    events_text = "\n".join(
        f"[{e.type.value}] {e.content}"
        + (f" (input: {e.tool_input})" if e.tool_input else "")
        + (f" (status: {e.tool_status})" if e.tool_status else "")
        + (f" (error: {e.tool_error})" if e.tool_error else "")
        for e in events
    )

    prompt = SUMMARIZE_PROMPT.format(events=events_text)
    logger.debug(f"Summarizing {len(events)} events via Ollama model {config.model}")

    try:
        response = requests.post(
            f"{config.ollama_host}/api/generate",
            json={
                "model": config.model,
                "prompt": prompt,
                "stream": False,
                "options": {
                    "num_predict": 500,  # Max output tokens
                    "temperature": 0.3,  # Lower temperature for summarization
                },
            },
            timeout=60,  # 60 second timeout
        )

        if response.status_code != 200:
            logger.error(f"Ollama API error: {response.status_code}")
            return Failure(f"Ollama API error: {response.status_code}")

        data = response.json()
        summary = data.get("response", "").strip()

        if not summary:
            logger.warning("Empty response from Ollama")
            return Failure("Empty response from Ollama")

        logger.info(
            f"Successfully summarized {len(events)} events ({len(summary)} chars)"
        )
        return Success(summary)

    except requests.exceptions.Timeout:
        logger.error(f"Ollama request timed out after 60s")
        return Failure("Ollama request timed out")
    except requests.exceptions.ConnectionError:
        logger.error(f"Cannot connect to Ollama at {config.ollama_host}")
        return Failure(f"Cannot connect to Ollama at {config.ollama_host}")
    except Exception as e:
        logger.exception(f"Ollama error: {e}")
        return Failure(f"Ollama error: {e}")
