"""AI Explainer - Uses AI to explain symptoms and provide recommendations."""

import json
import logging
from typing import Dict, List, Any, Optional
from doctor.diagnostics.symptoms import Symptom
from doctor.diagnostics.rules import DiagnosticRule
from doctor.ai.prompt import build_explanation_prompt
from doctor.ai.schema import DiagnosticReport, validate_report


logger = logging.getLogger(__name__)


class AIExplainer:
    """Handles AI-powered explanation of diagnostic results."""
    
    def __init__(self, use_ai: bool = True):
        """
        Initialize AI explainer.
        
        Args:
            use_ai: Whether to use AI (if False, returns basic explanations).
        """
        self.use_ai = use_ai
    
    def explain(
        self,
        symptoms: List[Symptom],
        matching_rules: List[DiagnosticRule],
        telemetry: Dict[str, Any]
    ) -> DiagnosticReport:
        """
        Generate AI explanation for diagnostic results.
        
        Args:
            symptoms: List of detected symptoms.
            matching_rules: List of matching diagnostic rules.
            telemetry: Raw telemetry data.
            
        Returns:
            DiagnosticReport with explanations and recommendations.
        """
        if not self.use_ai or not symptoms:
            return self._generate_basic_report(symptoms, matching_rules, telemetry)
        
        prompt = build_explanation_prompt(symptoms, matching_rules, telemetry)
        
        try:
            # In Phase-1, we'll use a simple approach
            # For production, this would call an AI API
            response = self._call_ai(prompt, symptoms, matching_rules, telemetry)
            report_data = self._parse_response(response)
            return validate_report(report_data)
        except Exception as e:
            logger.error(f"AI explanation failed: {e}")
            return self._generate_basic_report(symptoms, matching_rules, telemetry)
    
    def _call_ai(
        self,
        prompt: str,
        symptoms: List[Symptom],
        matching_rules: List[DiagnosticRule],
        telemetry: Dict[str, Any]
    ) -> str:
        """
        Call AI service to generate explanation.
        
        In Phase-1, this is a placeholder that generates structured output.
        For Phase-2, this would integrate with an actual AI API.
        
        Args:
            prompt: The prompt to send to AI.
            
        Returns:
            JSON string response.
        """
        # Phase-1: Generate deterministic explanations based on symptoms
        # This simulates AI behavior but is rule-based for Phase-1
        logger.info("Generating AI explanation (Phase-1 mode)")
        
        # Parse symptoms to generate report
        issues = []
        for symptom in symptoms:
            issue = self._symptom_to_issue(symptom)
            if issue:
                issues.append(issue)
        
        summary = self._generate_summary(symptoms, issues)
        not_checked = [
            "Deep security vulnerability scanning",
            "Registry integrity analysis",
            "Configuration corruption heuristics",
            "Firmware diagnostics",
            "Kernel-level memory inspection",
            "Application-specific code analysis",
            "Malware detection",
            "Penetration testing"
        ]
        
        return json.dumps({
            "summary": summary,
            "issues": issues,
            "not_checked": not_checked
        })
    
    def _symptom_to_issue(self, symptom: Symptom) -> Optional[Dict[str, Any]]:
        """Convert a symptom to an issue explanation."""
        urgency_map = {
            "critical": "high",
            "high": "high",
            "medium": "medium",
            "low": "low"
        }
        
        explanations = {
            "cpu_pressure": {
                "explanation": f"CPU usage is high ({symptom.metadata.get('average_cpu', 0)}%), which can cause system slowdown.",
                "causes": [
                    "Background processes consuming resources",
                    "Heavy applications running",
                    "Malware or unwanted software",
                    "System updates in progress"
                ],
                "recommendations": [
                    "Close unnecessary applications",
                    "Check Task Manager (Windows) or Activity Monitor (macOS) for resource-heavy processes",
                    "Restart your computer if the issue persists",
                    "Check for system updates that might be running"
                ]
            },
            "memory_pressure": {
                "explanation": f"Memory usage is high ({symptom.metadata.get('percent', 0)}%), which can cause performance issues.",
                "causes": [
                    "Too many applications open",
                    "Memory leaks in applications",
                    "Insufficient RAM for workload",
                    "Background services using memory"
                ],
                "recommendations": [
                    "Close unused applications",
                    "Restart applications that seem to be using excessive memory",
                    "Restart your computer to free up memory",
                    "Consider upgrading RAM if this is a recurring issue"
                ]
            },
            "disk_space_critical": {
                "explanation": f"Disk space is critically low ({symptom.metadata.get('percent_used', 0)}% used) on {symptom.metadata.get('mountpoint', 'disk')}.",
                "causes": [
                    "Large files taking up space",
                    "Temporary files accumulation",
                    "Downloads folder full",
                    "System logs or cache files"
                ],
                "recommendations": [
                    "Delete unnecessary files and empty the trash",
                    "Clear browser cache and temporary files",
                    "Move large files to external storage",
                    "Uninstall unused applications",
                    "Use disk cleanup tools (built into OS)"
                ]
            },
            "disk_space_low": {
                "explanation": f"Disk space is running low ({symptom.metadata.get('percent_used', 0)}% used) on {symptom.metadata.get('mountpoint', 'disk')}.",
                "causes": [
                    "Files accumulating over time",
                    "Large media files",
                    "Application data and caches"
                ],
                "recommendations": [
                    "Review and delete unnecessary files",
                    "Clear application caches",
                    "Move files to external storage or cloud",
                    "Consider disk cleanup"
                ]
            },
            "battery_critical": {
                "explanation": f"Battery is critically low ({symptom.metadata.get('percent', 0)}%), system may shut down soon.",
                "causes": [
                    "Battery not charging",
                    "High power consumption",
                    "Battery degradation"
                ],
                "recommendations": [
                    "Plug in power adapter immediately",
                    "Save all work",
                    "Close power-intensive applications",
                    "Check if charger is properly connected"
                ]
            },
            "battery_low": {
                "explanation": f"Battery is low ({symptom.metadata.get('percent', 0)}%), consider plugging in.",
                "causes": [
                    "Normal battery drain",
                    "Power-intensive applications running"
                ],
                "recommendations": [
                    "Plug in power adapter when possible",
                    "Reduce screen brightness",
                    "Close unnecessary applications",
                    "Enable power saving mode"
                ]
            },
            "network_dns_failure": {
                "explanation": "DNS resolution is failing, which prevents domain name lookups.",
                "causes": [
                    "DNS server configuration issues",
                    "Network connectivity problems",
                    "DNS server unreachable"
                ],
                "recommendations": [
                    "Check network connection",
                    "Verify DNS server settings",
                    "Try using alternative DNS servers (e.g., 8.8.8.8)",
                    "Restart network interface"
                ]
            },
            "network_gateway_unreachable": {
                "explanation": "Default gateway is unreachable, preventing internet connectivity.",
                "causes": [
                    "Router or gateway device down",
                    "Network configuration issues",
                    "Physical network problems"
                ],
                "recommendations": [
                    "Check router/gateway device status",
                    "Verify network cable connections",
                    "Restart network interface",
                    "Contact network administrator if on corporate network"
                ]
            },
            "network_high_latency": {
                "explanation": f"Network latency is elevated ({symptom.metadata.get('latency_ms', 0)}ms), which may affect responsiveness.",
                "causes": [
                    "Network congestion",
                    "Distance to servers",
                    "ISP routing issues"
                ],
                "recommendations": [
                    "Check for network congestion",
                    "Test connection to different servers",
                    "Contact ISP if issue persists",
                    "Consider wired connection if using Wi-Fi"
                ]
            },
            "network_interface_down": {
                "explanation": f"Network interface(s) are down: {', '.join(symptom.metadata.get('interfaces', []))}.",
                "causes": [
                    "Interface disabled",
                    "Driver issues",
                    "Physical connection problems"
                ],
                "recommendations": [
                    "Check physical cable connections",
                    "Verify interface is enabled in system settings",
                    "Restart network interface",
                    "Check for driver issues"
                ]
            },
            "application_crashes_frequent": {
                "explanation": f"Multiple application crashes detected ({symptom.metadata.get('crash_count', 0)} in last 24 hours), indicating system instability.",
                "causes": [
                    "Memory issues",
                    "Corrupted application files",
                    "Driver compatibility problems",
                    "System resource exhaustion"
                ],
                "recommendations": [
                    "Check system memory for errors",
                    "Update problematic applications",
                    "Review system logs for patterns",
                    "Consider system restart if crashes persist"
                ]
            },
            "application_crashes_elevated": {
                "explanation": f"Elevated application crash rate detected ({symptom.metadata.get('crash_count', 0)} in last 24 hours).",
                "causes": [
                    "Application-specific issues",
                    "Memory pressure",
                    "Resource conflicts"
                ],
                "recommendations": [
                    "Monitor which applications are crashing",
                    "Check available system resources",
                    "Update applications to latest versions",
                    "Review application logs"
                ]
            },
            "application_crashes_detected": {
                "explanation": f"Some application crashes observed ({symptom.metadata.get('crash_count', 0)} in last 24 hours).",
                "causes": [
                    "Normal application behavior",
                    "Temporary resource constraints",
                    "Application bugs"
                ],
                "recommendations": [
                    "Monitor crash frequency",
                    "Update applications if crashes increase",
                    "Check system resources"
                ]
            },
            "disk_io_errors_critical": {
                "explanation": f"Critical disk I/O errors detected on {symptom.metadata.get('disk', 'disk')} ({symptom.metadata.get('read_errors', 0)} read, {symptom.metadata.get('write_errors', 0)} write errors).",
                "causes": [
                    "Disk hardware failure",
                    "Corrupted filesystem",
                    "Failing storage device"
                ],
                "recommendations": [
                    "Backup data immediately",
                    "Run disk diagnostics",
                    "Consider replacing storage device",
                    "Check disk SMART status"
                ]
            },
            "disk_io_errors_elevated": {
                "explanation": f"Elevated disk I/O errors on {symptom.metadata.get('disk', 'disk')} ({symptom.metadata.get('read_errors', 0)} read, {symptom.metadata.get('write_errors', 0)} write errors).",
                "causes": [
                    "Disk wear",
                    "Filesystem issues",
                    "Storage device problems"
                ],
                "recommendations": [
                    "Monitor error rate",
                    "Run filesystem check",
                    "Backup important data",
                    "Check disk health status"
                ]
            },
            "hardware_temperature_critical": {
                "explanation": f"Critical temperature detected on {symptom.metadata.get('sensor', 'sensor')} ({symptom.metadata.get('temperature', 0)}°C).",
                "causes": [
                    "Insufficient cooling",
                    "Dust accumulation",
                    "Cooling fan failure",
                    "High ambient temperature"
                ],
                "recommendations": [
                    "Ensure adequate ventilation",
                    "Clean dust from cooling vents",
                    "Check cooling fan operation",
                    "Reduce system load if possible"
                ]
            },
            "hardware_temperature_elevated": {
                "explanation": f"Elevated temperature on {symptom.metadata.get('sensor', 'sensor')} ({symptom.metadata.get('temperature', 0)}°C).",
                "causes": [
                    "High system load",
                    "Insufficient cooling",
                    "Ambient temperature"
                ],
                "recommendations": [
                    "Ensure proper ventilation",
                    "Clean cooling vents",
                    "Monitor temperature trends",
                    "Reduce system load if needed"
                ]
            },
            "driver_instability_frequent": {
                "explanation": f"Frequent driver instability detected ({symptom.metadata.get('restart_count', 0)} restart events).",
                "causes": [
                    "Driver compatibility issues",
                    "Hardware problems",
                    "Driver corruption",
                    "System resource conflicts"
                ],
                "recommendations": [
                    "Update drivers to latest versions",
                    "Check for hardware issues",
                    "Review system logs for patterns",
                    "Consider driver reinstallation"
                ]
            },
            "driver_instability_detected": {
                "explanation": f"Driver instability signals detected ({symptom.metadata.get('restart_count', 0)} restart events).",
                "causes": [
                    "Driver issues",
                    "Hardware compatibility",
                    "System conflicts"
                ],
                "recommendations": [
                    "Monitor driver stability",
                    "Update drivers if available",
                    "Check system logs",
                    "Review hardware compatibility"
                ]
            },
            "security_firewall_disabled": {
                "explanation": "Firewall appears to be disabled, reducing network protection.",
                "causes": [
                    "Firewall manually disabled",
                    "Security software configuration",
                    "System configuration changes"
                ],
                "recommendations": [
                    "Enable firewall in system settings",
                    "Review security configuration",
                    "Verify firewall status",
                    "Consider security implications"
                ]
            },
            "security_encryption_disabled": {
                "explanation": "Disk encryption appears to be disabled, data at rest is not encrypted.",
                "causes": [
                    "Encryption not enabled",
                    "Encryption disabled by user",
                    "System configuration"
                ],
                "recommendations": [
                    "Consider enabling disk encryption",
                    "Review security requirements",
                    "Understand encryption implications",
                    "Backup data before enabling encryption"
                ]
            },
            "security_updates_pending": {
                "explanation": "System updates are available, which may include security patches.",
                "causes": [
                    "Pending OS updates",
                    "Update schedule",
                    "Deferred updates"
                ],
                "recommendations": [
                    "Review available updates",
                    "Install updates when convenient",
                    "Check update release notes",
                    "Schedule update installation"
                ]
            }
        }
        
        issue_info = explanations.get(symptom.type)
        if not issue_info:
            return None
        
        return {
            "name": symptom.type.replace("_", " ").title(),
            "urgency": urgency_map.get(symptom.severity, "medium"),
            "explanation": issue_info["explanation"],
            "likely_causes": issue_info["causes"],
            "recommendations": issue_info["recommendations"],
            "confidence": 0.75 if symptom.severity in ["critical", "high"] else 0.65
        }
    
    def _generate_summary(self, symptoms: List[Symptom], issues: List[Dict[str, Any]]) -> str:
        """Generate a summary of system health."""
        if not symptoms:
            return "System appears healthy. No significant issues detected."
        
        critical_count = sum(1 for s in symptoms if s.severity == "critical")
        high_count = sum(1 for s in symptoms if s.severity == "high")
        
        if critical_count > 0:
            return f"System health is CRITICAL. {critical_count} critical issue(s) detected requiring immediate attention."
        elif high_count > 0:
            return f"System health needs attention. {high_count} high-priority issue(s) detected."
        else:
            return f"System is generally healthy with {len(symptoms)} minor issue(s) detected."
    
    def _parse_response(self, response: str) -> Dict[str, Any]:
        """
        Parse AI response JSON.
        
        Args:
            response: JSON string response.
            
        Returns:
            Parsed dictionary.
        """
        try:
            return json.loads(response)
        except json.JSONDecodeError as e:
            logger.error(f"Failed to parse AI response: {e}")
            raise
    
    def _generate_basic_report(
        self,
        symptoms: List[Symptom],
        matching_rules: List[DiagnosticRule],
        telemetry: Dict[str, Any]
    ) -> DiagnosticReport:
        """Generate a basic report without AI."""
        if not symptoms:
            return DiagnosticReport(
                summary="System appears healthy. No issues detected.",
                issues=[],
                not_checked=["AI-powered analysis"]
            )
        
        issues = []
        for symptom in symptoms:
            issue = self._symptom_to_issue(symptom)
            if issue:
                issues.append(issue)
        
        summary = self._generate_summary(symptoms, issues)
        
        return DiagnosticReport(
            summary=summary,
            issues=issues,
            not_checked=["AI-powered analysis", "Advanced diagnostics"]
        )
