"""Validate query results for business plausibility using local LLM."""

from __future__ import annotations

import json

from local_llm.ollama_client import OllamaClient


class PlausibilityChecker:
    """Uses local LLM to validate that query results make business sense."""

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

    async def check(
        self,
        question: str,
        sql: str,
        columns: list[str],
        row_count: int,
        sample_rows: list[dict],
    ) -> dict:
        """Check if results are plausible for the given question.

        This runs LOCALLY — the local LLM can see actual data.

        Returns:
            {"plausible": bool, "confidence": float, "notes": str}
        """
        # Limit sample data for the prompt
        sample_text = json.dumps(sample_rows[:5], indent=2, default=str)

        prompt = f"""Analyze whether these SQL query results are plausible for the given business question.

Question: {question}
SQL: {sql}
Columns: {', '.join(columns)}
Total rows: {row_count}
Sample data (first 5 rows):
{sample_text}

Evaluate:
1. Does the row count seem reasonable for this type of query?
2. Do the column names match what the question asks for?
3. Do the sample values look reasonable (no obvious errors like negative prices, future dates for historical data, etc.)?

Respond in JSON format:
{{"plausible": true/false, "confidence": 0.0-1.0, "notes": "brief explanation"}}"""

        response = await self._ollama.generate(
            prompt=prompt,
            system="You are a data quality analyst. Respond only with valid JSON.",
            temperature=0.1,
        )

        try:
            result = json.loads(response.strip())
            return {
                "plausible": bool(result.get("plausible", True)),
                "confidence": float(result.get("confidence", 0.5)),
                "notes": str(result.get("notes", "")),
            }
        except (json.JSONDecodeError, ValueError):
            return {"plausible": True, "confidence": 0.5, "notes": "Could not parse LLM response"}
