"""Diagnostic Analyzer - Orchestrates symptom detection and rule evaluation."""

import logging
from typing import Dict, List, Any
from doctor.core.telemetry import collect_all_telemetry
from doctor.diagnostics.symptoms import extract_all_symptoms, Symptom
from doctor.diagnostics.rules import evaluate_rules, DiagnosticRule


logger = logging.getLogger(__name__)


class DiagnosticResult:
    """Container for diagnostic analysis results."""
    
    def __init__(
        self,
        telemetry: Dict[str, Any],
        symptoms: List[Symptom],
        matching_rules: List[DiagnosticRule]
    ):
        self.telemetry = telemetry
        self.symptoms = symptoms
        self.matching_rules = matching_rules
    
    def get_issues_summary(self) -> Dict[str, Any]:
        """
        Get a summary of detected issues.
        
        Returns:
            Dictionary with issue summary.
        """
        critical_count = sum(1 for s in self.symptoms if s.severity == "critical")
        high_count = sum(1 for s in self.symptoms if s.severity == "high")
        medium_count = sum(1 for s in self.symptoms if s.severity == "medium")
        low_count = sum(1 for s in self.symptoms if s.severity == "low")
        
        return {
            "total_symptoms": len(self.symptoms),
            "critical": critical_count,
            "high": high_count,
            "medium": medium_count,
            "low": low_count,
            "matching_rules": len(self.matching_rules)
        }


def analyze_system() -> DiagnosticResult:
    """
    Perform complete system diagnostic analysis.
    
    Returns:
        DiagnosticResult with telemetry, symptoms, and matching rules.
    """
    logger.info("Starting system diagnostic analysis...")
    
    # Step 1: Collect telemetry
    telemetry = collect_all_telemetry()
    
    # Step 2: Extract symptoms
    symptoms = extract_all_symptoms(telemetry)
    
    # Step 3: Evaluate rules
    matching_rules = evaluate_rules(symptoms, telemetry)
    
    result = DiagnosticResult(telemetry, symptoms, matching_rules)
    
    summary = result.get_issues_summary()
    logger.info(
        f"Analysis complete: {summary['total_symptoms']} symptoms, "
        f"{summary['matching_rules']} rules matched"
    )
    
    return result
