# mlink-backend/scripts/log_analyzer.py
import re
import json
from collections import Counter, defaultdict
from datetime import datetime, timedelta

class LogAnalyzer:
    """로그 분석 클래스"""
    
    def __init__(self, log_file: str):
        self.log_file = log_file
    
    def analyze_errors(self, hours: int = 24):
        """에러 분석"""
        errors = []
        with open(self.log_file, 'r', encoding='utf-8') as f:
            for line in f:
                if 'ERROR' in line:
                    errors.append(line.strip())
        
        error_counts = Counter()
        for error in errors:
            # 에러 타입 추출
            match = re.search(r'event_type=\'(\w+)\'', error)
            if match:
                error_counts[match.group(1)] += 1
        
        return dict(error_counts)
    
    def analyze_api_performance(self, hours: int = 24):
        """API 성능 분석"""
        api_calls = []
        with open(self.log_file, 'r', encoding='utf-8') as f:
            for line in f:
                if 'api_response' in line:
                    # 응답 시간 추출
                    match = re.search(r'response_time=([\d.]+)', line)
                    if match:
                        api_calls.append(float(match.group(1)))
        
        if api_calls:
            return {
                'total_calls': len(api_calls),
                'avg_response_time': sum(api_calls) / len(api_calls),
                'max_response_time': max(api_calls),
                'min_response_time': min(api_calls)
            }
        return {}