"""AI Prompt Builder - Constructs prompts for AI explanation."""

from typing import Dict, List, Any
from doctor.diagnostics.symptoms import Symptom
from doctor.diagnostics.rules import DiagnosticRule
from doctor.core.os_detect import detect_os


def build_explanation_prompt(
    symptoms: List[Symptom],
    matching_rules: List[DiagnosticRule],
    telemetry: Dict[str, Any]
) -> str:
    """
    Build a prompt for AI to explain symptoms and provide recommendations.
    
    Args:
        symptoms: List of detected symptoms.
        matching_rules: List of matching diagnostic rules.
        telemetry: Raw telemetry data.
        
    Returns:
        Formatted prompt string.
    """
    os_info = detect_os()
    
    prompt = f"""You are a Device Doctor diagnostic assistant. Your role is to explain system issues clearly and recommend safe, manual actions.

CRITICAL CONSTRAINTS:
- You MUST return valid JSON only, matching the exact schema provided
- NEVER suggest commands, scripts, or automated fixes
- NEVER suggest system-level changes (registry edits, driver updates, etc.)
- ONLY suggest safe, manual actions that users can perform themselves
- State uncertainty explicitly when confidence is low
- Be clear and concise for non-technical users

SYSTEM INFORMATION:
- OS: {os_info['name']} {os_info['version']}
- Architecture: {os_info['arch']}
- Platform: {os_info['platform']}

DETECTED SYMPTOMS:
"""
    
    if not symptoms:
        prompt += "- No symptoms detected - system appears healthy\n"
    else:
        for i, symptom in enumerate(symptoms, 1):
            prompt += f"""
{i}. Type: {symptom.type}
   Severity: {symptom.severity}
   Duration: {symptom.duration}
   Impact: {', '.join(symptom.impact)}
   Metadata: {symptom.metadata}
"""
    
    prompt += f"""
MATCHING DIAGNOSTIC RULES:
"""
    
    if not matching_rules:
        prompt += "- No rules matched\n"
    else:
        for i, rule in enumerate(matching_rules, 1):
            prompt += f"{i}. {rule.name} (Urgency: {rule.urgency}, Category: {rule.category})\n"
    
    prompt += f"""
TELEMETRY SUMMARY:
- CPU Usage: {telemetry.get('cpu', {}).get('average', 0)}% average, {telemetry.get('cpu', {}).get('max', 0)}% max
- Memory Usage: {telemetry.get('memory', {}).get('percent', 0)}% ({telemetry.get('memory', {}).get('available_gb', 0)} GB available)
- Disk Partitions: {len(telemetry.get('disk', []))} checked
- System Uptime: {telemetry.get('uptime', {}).get('days', 0)} days
- Top Processes: {len(telemetry.get('top_processes', []))} listed

YOUR TASK:
Analyze the symptoms and provide:
1. A brief summary of overall system health
2. For each significant issue:
   - A clear, plain-English explanation
   - Likely causes (ranked by probability)
   - Safe, manual recommendations (what the user can do themselves)
   - Your confidence level (0.0 to 1.0)
3. List what was NOT checked (for transparency)

Remember:
- Be honest about uncertainty
- Avoid technical jargon when possible
- Focus on actionable, safe recommendations
- Never suggest automated fixes or commands

Return ONLY valid JSON matching this schema:
{{
  "summary": "Brief summary of system health",
  "issues": [
    {{
      "name": "Issue name",
      "urgency": "high|medium|low",
      "explanation": "What's happening",
      "likely_causes": ["cause1", "cause2"],
      "recommendations": ["manual action 1", "manual action 2"],
      "confidence": 0.85
    }}
  ],
  "not_checked": ["item1", "item2"]
}}
"""
    
    return prompt
