"""Report Formatter - Formats diagnostic reports for human reading."""

import logging
from typing import Dict, Any, List
from doctor.ai.schema import DiagnosticReport
from doctor.report.health_score import calculate_health_score
from doctor.diagnostics.symptoms import Symptom


logger = logging.getLogger(__name__)


def format_report(
    report: DiagnosticReport,
    symptoms: List[Symptom],
    telemetry: Dict[str, Any]
) -> str:
    """
    Format diagnostic report as human-readable text.
    
    Args:
        report: DiagnosticReport from AI explainer.
        symptoms: List of detected symptoms.
        telemetry: Raw telemetry data.
        
    Returns:
        Formatted report string.
    """
    health_score = calculate_health_score(symptoms)
    
    output = []
    output.append("=" * 70)
    output.append("DEVICE DOCTOR - SYSTEM HEALTH REPORT")
    output.append("=" * 70)
    output.append("")
    
    # Health Score
    output.append(f"Overall Health Score: {health_score['score']}/100 ({health_score['grade']})")
    output.append(f"Status: {health_score['status'].upper()}")
    output.append("")
    
    # Summary
    output.append("SUMMARY")
    output.append("-" * 70)
    output.append(report.summary)
    output.append("")
    
    # Issues
    if report.issues:
        output.append("DETECTED ISSUES")
        output.append("-" * 70)
        
        for i, issue in enumerate(report.issues, 1):
            output.append(f"\n{i}. {issue.name.upper()}")
            output.append(f"   Urgency: {issue.urgency.upper()}")
            output.append(f"   Confidence: {issue.confidence * 100:.0f}%")
            output.append("")
            output.append(f"   Explanation:")
            output.append(f"   {issue.explanation}")
            output.append("")
            
            if issue.likely_causes:
                output.append("   Likely Causes:")
                for cause in issue.likely_causes:
                    output.append(f"   - {cause}")
                output.append("")
            
            if issue.recommendations:
                output.append("   Recommendations:")
                for rec in issue.recommendations:
                    output.append(f"   - {rec}")
                output.append("")
            
            output.append("-" * 70)
    else:
        output.append("DETECTED ISSUES")
        output.append("-" * 70)
        output.append("No issues detected. System appears healthy.")
        output.append("")
    
    # What was not checked
    if report.not_checked:
        output.append("NOT CHECKED (Limitations)")
        output.append("-" * 70)
        for item in report.not_checked:
            output.append(f"- {item}")
        output.append("")
    
    # System Information
    output.append("SYSTEM INFORMATION")
    output.append("-" * 70)
    os_info = telemetry.get("os", {})
    output.append(f"OS: {os_info.get('name', 'Unknown')} {os_info.get('version', '')}")
    output.append(f"Architecture: {os_info.get('arch', 'Unknown')}")
    output.append(f"Uptime: {telemetry.get('uptime', {}).get('days', 0):.1f} days")
    output.append("")
    
    # Telemetry Summary
    output.append("TELEMETRY SUMMARY")
    output.append("-" * 70)
    cpu = telemetry.get("cpu", {})
    output.append(f"CPU Usage: {cpu.get('average', 0)}% average, {cpu.get('max', 0)}% max")
    
    memory = telemetry.get("memory", {})
    output.append(f"Memory Usage: {memory.get('percent', 0)}% ({memory.get('available_gb', 0)} GB available)")
    
    disk = telemetry.get("disk", [])
    if disk:
        output.append("Disk Usage:")
        for d in disk:
            output.append(f"  {d.get('mountpoint', 'Unknown')}: {d.get('percent', 0)}% used "
                         f"({d.get('free_gb', 0)} GB free)")
    
    battery = telemetry.get("battery")
    if battery:
        output.append(f"Battery: {battery.get('percent', 0)}% "
                     f"{'(plugged in)' if battery.get('plugged') else '(not plugged)'}")
    
    output.append("")
    output.append("=" * 70)
    output.append("Report generated by Device Doctor (Phase-1 Read-Only)")
    output.append("=" * 70)
    
    return "\n".join(output)


def format_json_report(
    report: DiagnosticReport,
    symptoms: List[Symptom],
    telemetry: Dict[str, Any]
) -> str:
    """
    Format diagnostic report as JSON.
    
    Args:
        report: DiagnosticReport from AI explainer.
        symptoms: List of detected symptoms.
        telemetry: Raw telemetry data.
        
    Returns:
        JSON string.
    """
    import json
    
    health_score = calculate_health_score(symptoms)
    
    json_data = {
        "health_score": health_score,
        "summary": report.summary,
        "issues": [issue.model_dump() for issue in report.issues],
        "not_checked": report.not_checked,
        "telemetry_summary": {
            "cpu": telemetry.get("cpu", {}),
            "memory": telemetry.get("memory", {}),
            "disk_count": len(telemetry.get("disk", [])),
            "uptime_days": telemetry.get("uptime", {}).get("days", 0)
        }
    }
    
    return json.dumps(json_data, indent=2)
