"""Health Score Calculator - Computes overall system health score."""

import logging
from typing import Dict, List, Any
from doctor.diagnostics.symptoms import Symptom


logger = logging.getLogger(__name__)


def calculate_health_score(symptoms: List[Symptom]) -> Dict[str, Any]:
    """
    Calculate overall system health score.
    
    Args:
        symptoms: List of detected symptoms.
        
    Returns:
        Dictionary with score and breakdown.
    """
    if not symptoms:
        return {
            "score": 100,
            "grade": "A",
            "status": "excellent",
            "breakdown": {}
        }
    
    # Weight symptoms by severity
    severity_weights = {
        "critical": 30,
        "high": 15,
        "medium": 5,
        "low": 2
    }
    
    total_penalty = 0
    breakdown = {}
    
    for symptom in symptoms:
        weight = severity_weights.get(symptom.severity, 0)
        total_penalty += weight
        
        symptom_type = symptom.type
        if symptom_type not in breakdown:
            breakdown[symptom_type] = {
                "count": 0,
                "max_severity": symptom.severity,
                "penalty": 0
            }
        
        breakdown[symptom_type]["count"] += 1
        breakdown[symptom_type]["penalty"] += weight
        
        # Update max severity
        severity_order = ["low", "medium", "high", "critical"]
        current_max = breakdown[symptom_type]["max_severity"]
        if severity_order.index(symptom.severity) > severity_order.index(current_max):
            breakdown[symptom_type]["max_severity"] = symptom.severity
    
    # Calculate score (0-100 scale)
    score = max(0, 100 - total_penalty)
    
    # Determine grade
    if score >= 90:
        grade = "A"
        status = "excellent"
    elif score >= 75:
        grade = "B"
        status = "good"
    elif score >= 60:
        grade = "C"
        status = "fair"
    elif score >= 40:
        grade = "D"
        status = "poor"
    else:
        grade = "F"
        status = "critical"
    
    return {
        "score": round(score, 1),
        "grade": grade,
        "status": status,
        "breakdown": breakdown,
        "total_penalty": total_penalty
    }
