"""LLM-powered dataset quality evaluation."""

from __future__ import annotations

import json
import logging

from bilgeai.analyzer.models import DatasetInsights, DatasetProfile
from bilgeai.core.exceptions import LLMError
from bilgeai.llm.base import LLMClient
from bilgeai.llm.prompts import EVALUATE_DATASET_PROMPT, SYSTEM_PROMPT

logger = logging.getLogger(__name__)


class LLMDatasetEvaluator:
    """LLM-powered dataset quality evaluation."""

    def __init__(self, client: LLMClient) -> None:
        self.client = client

    def evaluate(
        self,
        profile: DatasetProfile,
        sample_rows: list[dict],
        model_name: str = "meta-llama/Llama-3-8B",
    ) -> DatasetInsights:
        """Send dataset profile + sample rows to LLM for evaluation."""
        prompt = EVALUATE_DATASET_PROMPT.format(
            dataset_json=json.dumps(
                profile.model_dump(exclude={"quality_issues", "pii_findings"}),
                indent=2,
                default=str,
            ),
            sample_rows_json=json.dumps(sample_rows[:10], indent=2, ensure_ascii=False),
            model_name=model_name,
        )

        try:
            if hasattr(self.client, "generate_structured"):
                response = self.client.generate_structured(prompt, system=SYSTEM_PROMPT)
            else:
                response = self.client.generate(prompt, system=SYSTEM_PROMPT)

            content = response.content.strip()
            try:
                data = json.loads(content)
            except (json.JSONDecodeError, ValueError):
                from bilgeai.llm.remote import _extract_json_from_response

                data = _extract_json_from_response(content)

            return DatasetInsights.model_validate(data)

        except LLMError:
            raise
        except Exception as e:
            logger.warning("LLM dataset evaluation failed: %s", e)
            raise LLMError(
                f"Dataset evaluation failed: {e}",
                suggestion="Check your API connection.",
            ) from e
