import psutil
import logging
from typing import Dict, Any
import time

logger = logging.getLogger(__name__)

class SystemMonitor:
    """시스템 상태 모니터링"""
    
    def __init__(self):
        self.start_time = time.time()
        self.memory_usage = []
        self.cpu_usage = []
    
    def log_system_status(self, stage: str):
        """시스템 상태 로깅"""
        memory_percent = psutil.virtual_memory().percent
        cpu_percent = psutil.cpu_percent()
        
        self.memory_usage.append(memory_percent)
        self.cpu_usage.append(cpu_percent)
        
        logger.info(f"System status at {stage}: CPU {cpu_percent}%, Memory {memory_percent}%")
        
        # 메모리 사용량이 90% 이상이면 경고
        if memory_percent > 90:
            logger.warning(f"High memory usage detected: {memory_percent}%")
    
    def get_performance_summary(self) -> Dict[str, Any]:
        """성능 요약 반환"""
        elapsed_time = time.time() - self.start_time
        
        return {
            'elapsed_time': elapsed_time,
            'avg_memory_usage': sum(self.memory_usage) / len(self.memory_usage) if self.memory_usage else 0,
            'max_memory_usage': max(self.memory_usage) if self.memory_usage else 0,
            'avg_cpu_usage': sum(self.cpu_usage) / len(self.cpu_usage) if self.cpu_usage else 0,
            'max_cpu_usage': max(self.cpu_usage) if self.cpu_usage else 0
        }
