"""
Explainable root-cause analysis for Sentinel Brain.
"""

from dataclasses import dataclass

from sentinel.brain.findings import Finding


@dataclass(frozen=True)
class RootCauseResult:
    """
    Root-cause conclusion returned by Sentinel Brain.

    Attributes:
        code: Stable machine-readable cause identifier.
        label: Human-readable probable cause.
        confidence: Confidence percentage from 0 to 100.
        explanation: Explainable reason for the conclusion.
        recommendation: Recommended technical action.
    """

    code: str
    label: str
    confidence: float
    explanation: str
    recommendation: str


class RootCauseAnalyzer:
    """
    Infer a probable technical cause from explainable findings.

    This V1 is intentionally rule-based and conservative.
    It never claims a confirmed diagnosis.
    """

    @staticmethod
    def _codes(
        findings: list[Finding],
    ) -> set[str]:
        """
        Return all finding codes.
        """
        return {
            finding.code
            for finding in findings
        }

    @classmethod
    def analyze(
        cls,
        findings: list[Finding],
    ) -> RootCauseResult:
        """
        Infer the most probable root cause.

        Args:
            findings: Explainable findings produced by the Brain.

        Returns:
            Conservative root-cause result.
        """
        codes = cls._codes(findings)

        sensor_problem_codes = {
            code
            for code in codes
            if (
                "SIGNAL_FROZEN" in code
                or "IMPOSSIBLE_JUMP" in code
                or "IMPLAUSIBLE_VALUE" in code
                or "DATA_MISSING" in code
                or "DATA_INCOMPLETE" in code
            )
        }

        if sensor_problem_codes:
            return RootCauseResult(
                code="SENSOR_INSTRUMENTATION_FAULT",
                label="Sensor or instrumentation fault",
                confidence=95.0,
                explanation=(
                    "One or more sensor signals are missing, frozen, "
                    "implausible or changing too quickly to represent "
                    "normal equipment behavior."
                ),
                recommendation=(
                    "Inspect sensor wiring, connectors, probe placement "
                    "and acquisition electronics before diagnosing the "
                    "refrigeration system."
                ),
            )

        if (
            "COMPRESSOR_CURRENT_RISING_FAST" in codes
            and "COMPRESSOR_TEMP_RISING_FAST" in codes
            and (
                "COOLING_EFFORT_INCREASED" in codes
                or "EVAPORATOR_DELTA_DEVIATION" in codes
            )
        ):
            return RootCauseResult(
                code="COMPRESSOR_EFFICIENCY_DEGRADATION",
                label="Probable compressor efficiency degradation",
                confidence=90.0,
                explanation=(
                    "Compressor temperature and electrical load are "
                    "increasing while cooling performance is deviating "
                    "from the equipment baseline."
                ),
                recommendation=(
                    "Inspect compressor condition, condenser airflow, "
                    "fan operation and refrigeration circuit loading."
                ),
            )

        if (
            "COOLING_EFFORT_INCREASED" in codes
            and (
                "COMPRESSOR_TEMP_RISING" in codes
                or "COMPRESSOR_TEMP_BASELINE_DRIFT" in codes
                or "COMPRESSOR_TEMP_BASELINE_DEVIATION" in codes
            )
            and "COMPRESSOR_CURRENT_RISING_FAST" not in codes
        ):
            return RootCauseResult(
                code="POOR_HEAT_REJECTION",
                label="Probable condenser airflow or heat rejection issue",
                confidence=84.0,
                explanation=(
                    "The compressor is operating hotter than its baseline "
                    "without a proportionally severe electrical increase. "
                    "This pattern is compatible with reduced heat rejection."
                ),
                recommendation=(
                    "Inspect condenser cleanliness, ventilation openings, "
                    "ambient airflow and condenser fan operation."
                ),
            )

        if (
            "INTERNAL_TEMP_RISING_FAST" in codes
            and (
                "COMPRESSOR_CURRENT_RISING_FAST" not in codes
                and "COMPRESSOR_CURRENT_RISING" not in codes
            )
            and (
                "EVAPORATOR_DELTA_BASELINE_OK" in codes
                or "EVAPORATOR_DELTA_STABLE" in codes
            )
        ):
            return RootCauseResult(
                code="EXTERNAL_THERMAL_LOAD",
                label="Probable external thermal load or door event",
                confidence=76.0,
                explanation=(
                    "Internal temperature is rising while evaporator "
                    "behavior and compressor electrical load do not show "
                    "a matching equipment degradation pattern."
                ),
                recommendation=(
                    "Check door closure, gasket condition, recent loading, "
                    "access events and room conditions."
                ),
            )

        if (
            "EVAPORATOR_DELTA_DEVIATION" in codes
            and (
                "COOLING_EFFORT_INCREASED" in codes
                or "COOLING_EFFORT_DRIFT" in codes
            )
        ):
            return RootCauseResult(
                code="REFRIGERATION_PERFORMANCE_DEGRADATION",
                label="Probable refrigeration performance degradation",
                confidence=86.0,
                explanation=(
                    "The evaporator temperature difference and compressor "
                    "effort both deviate from the equipment-specific baseline."
                ),
                recommendation=(
                    "Inspect airflow, icing, refrigerant circuit condition, "
                    "evaporator loading and condenser performance."
                ),
            )

        if (
            "COMPRESSOR_CURRENT_RISING_FAST" in codes
            or "COMPRESSOR_CURRENT_BASELINE_DEVIATION" in codes
        ):
            return RootCauseResult(
                code="ELECTRICAL_OR_MECHANICAL_LOAD_INCREASE",
                label="Probable electrical or mechanical load increase",
                confidence=82.0,
                explanation=(
                    "Compressor current has increased significantly relative "
                    "to its historical behavior."
                ),
                recommendation=(
                    "Inspect supply voltage, start components, compressor "
                    "mechanical load and electrical connections."
                ),
            )

        significant_findings = [
            finding
            for finding in findings
            if finding.severity != "INFO"
        ]

        if not significant_findings:
            return RootCauseResult(
                code="NO_ANOMALY_DETECTED",
                label="No anomaly detected",
                confidence=95.0,
                explanation=(
                    "Thermal, electrical, cooling and sensor indicators "
                    "remain stable and consistent with this equipment's "
                    "baseline."
                ),
                recommendation="No action required.",
            )

        most_severe = max(
            significant_findings,
            key=lambda finding: {
                "LOW": 1,
                "MEDIUM": 2,
                "HIGH": 3,
                "CRITICAL": 4,
            }.get(finding.severity, 0),
        )

        return RootCauseResult(
            code="UNCLASSIFIED_DEVIATION",
            label="Unclassified equipment deviation",
            confidence=max(
                55.0,
                min(80.0, most_severe.confidence - 10.0),
            ),
            explanation=(
                "Sentinel detected a meaningful deviation, but the current "
                "combination of indicators is not sufficient to identify "
                "one probable technical cause."
            ),
            recommendation=(
                "Review the explainable findings and continue monitoring. "
                "Plan a technical inspection if the deviation persists."
            ),
        )
