"""Upload evaluation results to Klira Hub.

DEPRECATED: This module is deprecated and will be removed in v2.0.

The new trace-based evaluation model sends traces directly to the platform
via OTLP. Results are generated by the platform and fetched via API.
HubUploader is no longer used in the evaluate() flow.
"""

import warnings
from typing import Dict, Any, Optional

import requests

from klira.sdk.evals.types import KliraEvalResult, ComplianceReport


class HubUploader:
    """Uploads evaluation results to Klira Hub API.

    DEPRECATED: This class is deprecated and will be removed in v2.0.

    The new trace-based evaluation model sends traces to the platform
    for evaluation. Results are generated by the platform and can be
    fetched via the platform API.

    This class is kept for backward compatibility but is no longer called
    from evaluate(). If you need to submit results to an API, please use
    the platform's evaluation endpoint instead.
    """

    def __init__(
        self,
        api_key: str,
        hub_url: str = "https://api.getklira.com",
    ):
        warnings.warn(
            "HubUploader is deprecated and will be removed in v2.0. "
            "The new trace-based evaluation model sends traces to /evals. "
            "Results are generated by the platform and fetched via API. "
            "See: https://docs.getklira.com/evals/trace-based-model for details.",
            DeprecationWarning,
            stacklevel=2,
        )
        self.api_key = api_key
        self.hub_url = hub_url.rstrip("/")
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        }

    def upload_results(
        self, result: KliraEvalResult, experiment_id: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        Upload evaluation results to Hub.

        Args:
            result: Complete evaluation result
            experiment_id: Optional experiment ID

        Returns:
            Response from Hub API with eval_run_id and URL
        """
        # Prepare payload
        payload = {
            "experiment_id": experiment_id,
            "dataset_path": result.dataset_path,
            "pass_rate": result.pass_rate,
            "total_test_cases": result.total_test_cases,
            "passed_test_cases": result.passed_test_cases,
            "failed_test_cases": result.failed_test_cases,
            "avg_scores": result.avg_scores,
            "compliance_report": (
                self._serialize_compliance_report(result.compliance_report)
                if result.compliance_report is not None
                else None
            ),
            "created_at": result.created_at.isoformat() if result.created_at else None,
            "duration_seconds": result.duration_seconds,
            # TODO: Add detailed test case results
        }

        # Upload to Hub
        response = requests.post(
            f"{self.hub_url}/api/v1/eval-runs",
            headers=self.headers,
            json=payload,
            timeout=30,
        )

        response.raise_for_status()
        return response.json()

    def _serialize_compliance_report(self, report: ComplianceReport) -> Dict[str, Any]:
        """Convert ComplianceReport to JSON-serializable dict."""
        return {
            "guardrail_recall": report.guardrail_recall,
            "guardrail_precision": report.guardrail_precision,
            "policy_coverage_rate": report.policy_coverage_rate,
            "avg_confidence": report.avg_confidence,
            "policy_metrics": report.policy_metrics,
            "untested_policies": report.untested_policies,
            "layer_distribution": report.layer_distribution,
            "low_confidence_count": report.low_confidence_count,
            "llm_fallback_rate": report.llm_fallback_rate,
            "recommendations": report.recommendations or [],
        }
