"""MongoDB contract adapters for analyzer outputs."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any, Dict, List, Optional

from .common import map_impact_to_severity, map_provider

if TYPE_CHECKING:
    from iqtoolkit_contracts import AnalysisResultV2


def build_results_from_report(
    report: Dict[str, Any],
    provider: Optional[str] = None,
) -> List["AnalysisResultV2"]:
    """Convert MongoDB analysis report dict into contract results."""
    from iqtoolkit_contracts import (
        AIRecommendation,
        AnalysisFinding,
        AnalysisResultV2,
        DatabaseType,
        QueryInfo,
    )

    results: List[AnalysisResultV2] = []
    mapped_provider = map_provider(provider)

    slow_queries = report.get("slow_queries", [])
    summary = report.get("summary", {})
    realtime_insights = report.get("realtime_metrics", {}).get("insights", [])

    for index, query in enumerate(slow_queries):
        query_text = str(query.get("query_shape") or query.get("command") or "")
        avg_duration = float(
            query.get("avg_duration_ms") or query.get("duration_ms") or 0.0
        )
        impact_score = float(query.get("impact_score") or 0.0)
        frequency = int(query.get("frequency") or 1)

        query_info = QueryInfo(
            query_text=query_text,
            duration_ms=avg_duration,
            source="mongodb_profiler",
            database_type=DatabaseType.MONGODB,
        )

        findings: List[AnalysisFinding] = [
            AnalysisFinding(
                name="Slow operation",
                description=(
                    f"Average duration {avg_duration:.2f} ms across {frequency} "
                    "executions."
                ),
                severity=map_impact_to_severity(impact_score),
                impact=f"Impact score {impact_score:.2f}",
                fix_suggestion=None,
            )
        ]

        for suggestion in query.get("optimization_suggestions", [])[:3]:
            findings.append(
                AnalysisFinding(
                    name="Optimization suggestion",
                    description=str(suggestion),
                    severity=map_impact_to_severity(impact_score),
                    impact=None,
                    fix_suggestion=str(suggestion),
                )
            )

        ai_recommendations: List[AIRecommendation] = []
        recommendations = report.get("recommendations") or []
        if mapped_provider is not None and recommendations and index == 0:
            ai_recommendations.append(
                AIRecommendation(
                    provider=mapped_provider,
                    model=None,
                    recommendation=str(recommendations[0]),
                    confidence=None,
                )
            )

        results.append(
            AnalysisResultV2(
                query=query_info,
                findings=findings,
                recommendations=ai_recommendations,
                severity=map_impact_to_severity(impact_score),
                summary={
                    "summary": summary,
                    "realtime_insights": realtime_insights,
                    "impact_score": impact_score,
                },
            )
        )

    return results
