"""Generate natural language summaries of query results using local LLM."""

from __future__ import annotations

import json

from local_llm.ollama_client import OllamaClient


class Summarizer:
    """Generates NL summaries of query results — runs locally, can see data."""

    def __init__(self, ollama: OllamaClient) -> None:
        self._ollama = ollama

    async def summarize(
        self,
        question: str,
        columns: list[str],
        row_count: int,
        sample_rows: list[dict],
        column_descriptions: dict[str, str] | None = None,
    ) -> str:
        """Generate a natural language summary of query results.

        The local LLM sees the actual data to produce an accurate summary.
        """
        sample_text = json.dumps(sample_rows[:10], indent=2, default=str)

        col_info = ", ".join(columns)
        if column_descriptions:
            col_parts = []
            for c in columns:
                desc = column_descriptions.get(c)
                col_parts.append(f"{c} ({desc})" if desc else c)
            col_info = ", ".join(col_parts)

        prompt = f"""The user asked: "{question}"

The query returned {row_count} rows with columns: {col_info}

Here are the first rows of data:
{sample_text}

Write a concise, helpful answer to the user's question based on this data.
- Start by briefly explaining what each column represents (especially cryptic SAP abbreviations)
- Be specific with numbers and key findings
- If there are aggregations, mention the totals/averages
- If there are many rows, summarize the key patterns
- Note any data quality issues (spaces instead of NULL, empty values, inconsistent formats)
- Keep it under 3 paragraphs
- Use a professional, friendly tone"""

        return await self._ollama.generate(
            prompt=prompt,
            system="You are a helpful business analyst. Provide clear, actionable summaries of data. Always explain what cryptic column names mean in business terms.",
            temperature=0.3,
        )
