"""
Sentinel Expert Report V1.

This module does not calculate equipment health.
It converts an AnalysisResult into a structured report.
"""

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime
from typing import Any

from sentinel.i18n.translator import Translator


@dataclass(frozen=True)
class ExpertReport:
    """Structured multilingual Sentinel expert report."""

    equipment_id: str
    generated_at: str
    language: str
    title: str
    status: str
    summary: str
    root_cause: str
    prediction: str
    recommendation: str
    confidence: str

    def to_dict(self) -> dict[str, str]:
        """Return a JSON-serializable representation."""
        return {
            "equipment_id": self.equipment_id,
            "generated_at": self.generated_at,
            "language": self.language,
            "title": self.title,
            "status": self.status,
            "summary": self.summary,
            "root_cause": self.root_cause,
            "prediction": self.prediction,
            "recommendation": self.recommendation,
            "confidence": self.confidence,
        }


class ExpertReportBuilder:
    """
    Build a user-facing report from one Brain analysis.

    The analysis object may be a dataclass or any object exposing
    the expected attributes.
    """

    def __init__(
        self,
        translator: Translator | None = None,
    ) -> None:
        """Initialize the report builder."""
        self.translator = translator or Translator()

    @staticmethod
    def _value(
        analysis: Any,
        name: str,
        default: Any = None,
    ) -> Any:
        """Read one analysis attribute safely."""
        return getattr(
            analysis,
            name,
            default,
        )

    def build(
        self,
        equipment_id: str,
        analysis: Any,
        language: str = "en",
    ) -> ExpertReport:
        """Build one multilingual expert report."""
        health_score = float(
            self._value(
                analysis,
                "health_score",
                0.0,
            )
        )

        status_code = str(
            self._value(
                analysis,
                "status",
                "UNKNOWN",
            )
        )

        root_cause_code = str(
            self._value(
                analysis,
                "root_cause_code",
                "UNCLASSIFIED_DEVIATION",
            )
            or "UNCLASSIFIED_DEVIATION"
        )

        recommendation_code = (
            "NO_ACTION_REQUIRED"
            if status_code == "EXCELLENT"
            else "CONTINUE_MONITORING"
        )

        risk_index = self._value(
            analysis,
            "risk_index",
            None,
        )

        horizon = self._value(
            analysis,
            "prediction_horizon_days",
            None,
        )

        confidence_value = self._value(
            analysis,
            "prediction_confidence",
            self._value(
                analysis,
                "confidence",
                0.0,
            ),
        )

        summary = self.translator.translate(
            "report.summary",
            language=language,
            health_score=round(
                health_score,
                1,
            ),
            status=self.translator.translate(
                f"status.{status_code}",
                language=language,
            ),
        )

        root_cause = self.translator.translate(
            f"root_cause.{root_cause_code}",
            language=language,
        )

        if horizon is None:
            prediction = self.translator.translate(
                "prediction.no_horizon",
                language=language,
                risk_index=(
                    "—"
                    if risk_index is None
                    else round(float(risk_index), 1)
                ),
            )
        else:
            prediction = self.translator.translate(
                "prediction.horizon",
                language=language,
                horizon_days=int(horizon),
                risk_index=(
                    "—"
                    if risk_index is None
                    else round(float(risk_index), 1)
                ),
            )

        recommendation = self.translator.translate(
            f"recommendation.{recommendation_code}",
            language=language,
        )

        confidence = self.translator.translate(
            "report.confidence",
            language=language,
            confidence=round(
                float(confidence_value or 0.0),
                1,
            ),
        )

        return ExpertReport(
            equipment_id=equipment_id,
            generated_at=datetime.now().isoformat(
                timespec="seconds"
            ),
            language=language,
            title=self.translator.translate(
                "report.title",
                language=language,
            ),
            status=self.translator.translate(
                f"status.{status_code}",
                language=language,
            ),
            summary=summary,
            root_cause=root_cause,
            prediction=prediction,
            recommendation=recommendation,
            confidence=confidence,
        )
